拆分

你可以将字符串拆分为零件数组,除以分隔符

NSString * yourString = @"Stack,Exchange,Network";
NSArray * yourWords = [yourString componentsSeparatedByString:@","]; 
// Output: @[@"Stack", @"Exchange", @"Network"]

如果你需要拆分一组几个不同的分隔符,请使用 -[NSString componentsSeparatedByCharactersInSet:]

NSString * yourString = @"Stack Overflow+Documentation/Objective-C";
NSArray * yourWords = [yourString componentsSeparatedByCharactersInSet:
                      [NSCharacterSet characterSetWithCharactersInString:@"+/"]];
// Output: @[@"Stack Overflow", @"Documentation", @"Objective-C"]`

如果需要将字符串分解为单个字符,请循环字符串的长度并将每个字符转换为新字符串。

NSMutableArray * characters = [[NSMutableArray alloc] initWithCapacity:[yourString length]];
for (int i = 0; i < [myString length]; i++) {
    [characters addObject: [NSString stringWithFormat:@"%C", 
                                      [yourString characterAtIndex:i]];
}

长度示例中一样 ,请记住,此处的字符是 UTF-16 代码单元,不一定是用户视为字符的内容。如果你将这个循环与 @"🇮🇹" 一起使用,你会发现它被分成了四个部分。

要获取用户感知字符的列表,请使用 -enumerateSubstringsInRange:options:usingBlock:

NSMutableArray * characters = [NSMutableArray array];
[yourString enumerateSubstringsInRange:(NSRange){0, [yourString length]}
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString * substring, NSRange r, NSRange s, BOOL * b){
                                [characters addObject:substring];
                            }];

这样可以保留像意大利标志这样的字形簇作为单个子字符串。