string – Swift 2:迭代和大写/小写一些字符
发布时间:2020-12-14 05:23:13 所属栏目:百科 来源:网络整理
导读:我想通过将一些字符转换为大写,其他一些字符转换为小写来修改 Swift字符串. 在Obj-c我有以下内容: - (NSString*) lowercaseDestination:(NSString*) string { NSUInteger length = string.length; unichar buf[length+1]; [string getCharacters:buf]; BOOL
我想通过将一些字符转换为大写,其他一些字符转换为小写来修改
Swift字符串.
在Obj-c我有以下内容: - (NSString*) lowercaseDestination:(NSString*) string { NSUInteger length = string.length; unichar buf[length+1]; [string getCharacters:buf]; BOOL up = true; for (int i=0; i< length ; i++) { unichar chr = buf[i]; if( .... ) { buf[i] = toupper(chr); } else { buf[i] = tolower(chr); } } string = [NSString stringWithCharacters:buf length:length]; return string; 你会如何在Swift 2中做到这一点? 我没有找到任何Character方法来判断大小写. 将1个字符的字符串数组作为选项吗? (然后使用String方法来上下每个String
String有一个upperCaseString方法,但是Character没有.
原因是在德语等外来语言中,转换单一语言 大写字符可以导致多个字符: print("?".uppercaseString) // "SS" toupper / tolower函数不是Unicode安全的,不是 所以你可以枚举字符串字符,将每个字符转换为 func lowercaseDestination(str : String) -> String { var result = "" for c in str.characters { let s = String(c) if condition { result += s.lowercaseString } else { result += s.uppercaseString } } return result } 这可以更紧凑地写成 func lowercaseDestination(str : String) -> String { return "".join(str.characters.map { c -> String in let s = String(c) return condition ? s.lowercaseString : s.uppercaseString }) } 重新评论:如果条件需要检查多个 func lowercaseDestination(str : String) -> String { var result = "" let characters = Array(str.characters) for i in 0 ..< characters.count { let s = String(characters[i]) if condition { result += s.lowercaseString } else { result += s.uppercaseString } } return result } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |