简体   繁体   中英

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

由于字符串已经是一个字符数组,这似乎是多余的。

If you really need an NSArray of NSString s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM