iOS迭代NSString

时间:2012-02-06 13:33:57

标签: ios5 nsstring loops

迭代NSString的最佳方法是什么?代码如下:

int len = str.length;
for (int i = 0; i < len; ++i)
{
    unichar c = [str characterAtIndex:i];
    // do something with c
}
对我来说,看起来很难看。我更喜欢像

这样的东西
// does not compile, unfortunately
for (unichar c in str)
{
    // do something with c
}

有没有办法比我的第一个代码片段更优雅地编写它?

1 个答案:

答案 0 :(得分:0)

for(NSString *subString in yourString){
    NSLog("The Substring is: %@", subString);
    // do anything you want with the substring in this loop
}

这必须有效(如果没有,您可以将字符串定义为NSDictionary并重试)