views:

102

answers:

2

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:@""];
}
+5  A: 

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

Williham Totland
Yes, I was so intent on needing an array that I put all my focus on how to create that array. What I want to do is to perform some permutations on the string, which I can do just as easily on an NSMutableString without creating the array. Thanks for putting me on the right track.
Robert Höglund
+3  A: 

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.

Nikolai Ruhe