Objective-C Language Splitting


You can split a string into an array of parts, divided by a separator character.

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

If you need to split on a set of several different delimiters, use -[NSString componentsSeparatedByCharactersInSet:].

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

If you need to break a string into its individual characters, loop over the length of the string and convert each character into a new string.

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

As in the Length Example, keep in mind that a "character" here is a UTF-16 code unit, not necessarily what the user sees as a character. If you use this loop with @"🇮🇹", you'll see that it's split into four pieces.

In order to get a list of the user-perceived characters, use -enumerateSubstringsInRange:options:usingBlock:.

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

This preserves grapheme clusters like the Italian flag as a single substring.