Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:@""];
}
like image 245
Robert Höglund Avatar asked Mar 18 '10 10:03

Robert Höglund


People also ask

How do you split a string by a character?

You can split a string by each character using an empty string('') as the splitter. In the example below, we split the same message using an empty string. The result of the split will be an array containing all the characters in the message string.

How do I split a string into substrings?

Use the Split method when the substrings you want are separated by a known delimiting character (or characters). Regular expressions are useful when the string conforms to a fixed pattern. Use the IndexOf and Substring methods in conjunction when you don't want to extract all of the substrings in a string.

What is a split method?

The Split method extracts the substrings in this string that are delimited by one or more of the strings in the separator parameter, and returns those substrings as elements of an array. The Split method looks for delimiters by performing comparisons using case-sensitive ordinal sort rules.


2 Answers

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

like image 164
Williham Totland Avatar answered Nov 15 '22 05:11

Williham Totland


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.

like image 32
Nikolai Ruhe Avatar answered Nov 15 '22 06:11

Nikolai Ruhe