Is there a simple way to split a NSString into an array of characters?

纵然是瞬间 提交于 2019-11-26 06:09:08

问题


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\"

回答1:


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];



回答2:


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



回答3:


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




回答4:


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];
}


来源:https://stackoverflow.com/questions/15254031/is-there-a-simple-way-to-split-a-nsstring-into-an-array-of-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!