如何按字符串中的每个字符拆分NSString?

时间:2021-09-27 14:27:45

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?

我有以下代码,它按预期工作。我想知道是否有一种可接受的Cocoa方法将字符串拆分为数组,并将字符串的每个字符作为数组中的对象?

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

2 个解决方案

#1


8  

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

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

#2


3  

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

如果你真的需要一个NSAtrings的NSArray,每个NSAtrings一个字符,我认为你创建它的方式是可以的。

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.

但是,您的目的无法以更易读,更安全(和性能优化)的方式进行,这似乎是值得怀疑的。有一件事对我来说特别危险:将字符串拆分为unicode字符(大多数情况下)不会按照您的预期进行操作。有些字符由多个unicode代码点组成。并且有unicode代码点,实际上是多个字符。除非你知道这些(或者可以保证你的输入不包含任意字符串),否则你不应该在字符级别的unicode字符串中搜索。

#1


8  

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

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

#2


3  

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

如果你真的需要一个NSAtrings的NSArray,每个NSAtrings一个字符,我认为你创建它的方式是可以的。

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.

但是,您的目的无法以更易读,更安全(和性能优化)的方式进行,这似乎是值得怀疑的。有一件事对我来说特别危险:将字符串拆分为unicode字符(大多数情况下)不会按照您的预期进行操作。有些字符由多个unicode代码点组成。并且有unicode代码点,实际上是多个字符。除非你知道这些(或者可以保证你的输入不包含任意字符串),否则你不应该在字符级别的unicode字符串中搜索。