如何在 Swift 中将字符串转换"Hello"为数组?["H","e","l","l","o"]
"Hello"
["H","e","l","l","o"]
在 Objective-C 中,我使用了这个:
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]]; for (int i=0; i < [myString length]; i++) { NSString *ichar = [NSString stringWithFormat:@"%c", [myString characterAtIndex:i]]; [characters addObject:ichar]; }
在 Swift 中更容易:
let string : String = "Hello 🐶🐮 🇩🇪" let characters = Array(string) println(characters) // [H, e, l, l, o, , 🐶, 🐮, , 🇩🇪]
这使用了以下事实
Array
SequenceType
String
而且由于 Swift 字符串完全支持 Unicode,这甚至适用于“基本多语言平面”之外的字符(例如馃惗)和扩展字素簇(例如馃嚛馃嚜,它实际上由 两个 Unicode 标量组成)。
更新:从 Swift 2 开始, String不再符合 SequenceType,但该characters属性提供了 Unicode 字符序列:
characters
let string = "Hello 🐶🐮 🇩🇪" let **characters = Array(string.characters) print(characters)**
这也适用于 Swift 3 。
更新:从 Swift 4 开始, String它(再次)是其 Characters 的集合:
Character
let string = "Hello 🐶🐮 🇩🇪" let characters = Array(string) print(characters) // ["H", "e", "l", "l", "o", " ", "🐶", "🐮", " ", "🇩🇪"]