NSString到NSArray
我想分裂成一个NSArray
的NSString
。 例如,给出:
NSString *myString=@"ABCDEF";
我想要一个NSArray
像:
NSArray *myArray={A,B,C,D,E,F};
如何用Objective-C和Cocoa做到这一点?
NSMutableArray *letterArray = [NSMutableArray array]; NSString *letters = @"ABCDEF𝍱क्"; [letters enumerateSubstringsInRange:NSMakeRange(0, [letters length]) options:(NSStringEnumerationByComposedCharacterSequences) usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { [letterArray addObject:substring]; }]; for (NSString *i in letterArray){ NSLog(@"%@",i); }
结果是
A B C D E F 𝍱 क्
enumerateSubstringsInRange:options:usingBlock:
适用于iOS 4+可以枚举具有不同样式的string。 一个被称为NSStringEnumerationByComposedCharacterSequences
,什么会逐字逐句枚举,但是对代理对敏感,基本字符加上结合标记,Hangul jamo和印度语辅音聚类 ,都被称为组合字符
请注意, 接受的答案是 “吞咽” 𝍱
并将क्
分解为क
和。
NSMutableArray *chars = [[NSMutableArray alloc] initWithCapacity:[theString length]]; for (int i=0; i < [theString length]; i++) { NSString *ichar = [NSString stringWithFormat:@"%C", [theString characterAtIndex:i]]; [chars addObject:ichar]; }
转变
NSString * string = @"ABCDEF"; NSArray * array = [string componentsSeparatedByString:@" "]; //Notice that in this case I separated the objects by a space because that's the way they are separated in the string
logging
NSLog(@"%@", array);
这是控制台返回的内容
此链接包含的示例可以根据子string将string拆分为数组,并基于字符集中的string。 我希望这篇文章可以帮助你。
这里是代码片段
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]; }
没有循环,你可以使用这个:
NSString *myString = @"ABCDEF"; NSMutableString *tempStr =[[NSMutableString alloc] initWithString:myString]; if([myString length] != 0) { NSError *error = NULL; // declare regular expression object NSRegularExpression *regex =[NSRegularExpression regularExpressionWithPattern:@"(.)" options:NSMatchingReportCompletion error:&error]; // replace each match with matches character + <space> eg 'A' with 'A ' [regex replaceMatchesInString:tempStr options:NSMatchingReportCompletion range:NSMakeRange(0,[myString length]) withTemplate:@"$0 "]; // trim last <space> character [tempStr replaceCharactersInRange:NSMakeRange([tempStr length] - 1, 1) withString:@""]; // split into array NSArray * arr = [tempStr componentsSeparatedByString:@" "]; // print NSLog(@"%@",arr); }
这个解决scheme通过正则expression式的帮助在每个字符的前面添加空格,并使用componentsSeparatedByString
和<space>
来返回一个数组
在Swift中,这变得非常简单。
Swift 3:
myString.characters.map { String($0) }
Swift 4:
myString.map { String($0) }