Robert Höglund
Robert Höglund

Reputation: 10090

How do I split an NSString by each character in the string?

I have the following code, which works as I expect. What I would like to know if there is an accepted Cocoa way of splitting a string into an array with each character of the string as an object in an array?

- (NSString *)doStuffWithString:(NSString *)string {
    NSMutableArray *stringBuffer = [NSMutableArray arrayWithCapacity:[string length]];
    for (int i = 0; i < [string length]; i++) {
        [stringBuffer addObject:[NSString stringWithFormat:@"%C", [string characterAtIndex:i]]];
    }

    // doing stuff with the array

    return [stringBuffer componentsJoinedByString:@""];
}

Upvotes: 6

Views: 5379

Answers (2)

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81878

If you really need an NSArray of NSStrings of one character each, I think your way of creating it is OK.

But it appears questionable that your purpose cannot be done in a more readable, safe (and performance-optimized) way. One thing especially seem dangerous to me: Splitting strings into unicode characters is (most of the time) not doing what you might expect. There are characters that are composed of more than one unicode code point. and there are unicode code points that really are more than one character. Unless you know about these (or can guarantee that your input does not contain arbitrary strings) you shouldn’t poke around in unicode strings on the character level.

Upvotes: 3

Williham Totland
Williham Totland

Reputation: 29039

As a string is already an array of characters, that seems, ... redundant.

Upvotes: 8

Related Questions