有没有一种简单的方法可以将NSString拆分为字符数组? [英] Is there a simple way to split a NSString into an array of characters?

查看:258
本文介绍了有没有一种简单的方法可以将NSString拆分为字符数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法将NSString拆分为字符数组?实际上,最好的结果类型是NSString本身的集合,每个仅一个字符.

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.

是的,我知道我可以循环执行此操作,但是我想知道是否有一种更快的方法可以像使用C#中的LINQ那样使用任何现有方法或函数来执行此操作.

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#.

例如

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

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

推荐答案

您可以执行以下操作(如果要使用枚举器)

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

如果您最终真的希望在NSArray中使用它

And if you really wanted it in an NSArray finally

NSArray *fooChars = [NSArray arrayWithArray:characters];

这篇关于有没有一种简单的方法可以将NSString拆分为字符数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆