Is there a simple way to split a NSString into an

2020-01-24 10:20发布

Is there a simple way to split a NSString into an array of characters? It would actually be best if the resulting type were a collection of NSString's themselves, just one character each.

Yes, I know I can do this in a loop, but I'm wondering if there is a faster way to do this with any existing methods or functions the way you can with LINQ in C#.

e.g.

// I have this...
 NSString * fooString = @"Hello";

// And want this...
NSArray * fooChars; // <-- Contains the NSStrings, @"H", @"e", @"l", @"l" and @"o"

4条回答
太酷不给撩
2楼-- · 2020-01-24 10:25

convert it to NSData the [data bytes] will have a C string in the encoding that you pick [data length] bytes long.

查看更多
祖国的老花朵
3楼-- · 2020-01-24 10:43

Try this

NSMutableArray *array = [NSMutableArray array];
NSString *str = @"Hello";
for (int i = 0; i < [str length]; i++) {
    NSString *ch = [str substringWithRange:NSMakeRange(i, 1)];
    [array addObject:ch];
}
查看更多
神经病院院长
4楼-- · 2020-01-24 10:46

Be sure to care about that some characters like emoji and others may span a longer range than just one index.

Here's a category method for NSString

@implementation (SplitString)

- (NSArray *)splitString
{
    NSUInteger index = 0;
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:self.length];

    while (index < self.length) {
        NSRange range = [self rangeOfComposedCharacterSequenceAtIndex:index];
        NSString *substring = [self substringWithRange:range];
        [array addObject:substring];
        index = range.location + range.length;
    }

    return array;
}

@end
查看更多
做自己的国王
5楼-- · 2020-01-24 10:47

You could do something like this (if you want to use enumerators)

NSString *fooString = @"Hello";
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[fooString length]]; 

[fooString enumerateSubstringsInRange:NSMakeRange(0, fooString.length)
                              options:NSStringEnumerationByComposedCharacterSequences
                           usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
    [characters addObject:substring];
}];

And if you really wanted it in an NSArray finally

NSArray *fooChars = [NSArray arrayWithArray:characters];
查看更多
登录 后发表回答