2012-02-06 37 views
0

迭代NSString的最佳方式是什麼?代碼如下:iOS迭代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 
} 

有什麼辦法比我的第一個代碼片段更優雅地寫它?

+0

什麼是你想用字符串做?有很多內置的函數可以讓你跳過簡單的字符串迭代。 – DogEatDog 2012-07-12 01:37:00

+0

如果有人像我一樣登陸這個頁面,請勾選[answer](http://stackoverflow.com/questions/4158646/most-efficient-way-to-iterate-over-all-the-chars-in- an-nsstring) – 2017-03-04 03:07:52

回答

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

這必須工作(如果沒有,你可以定義你的字符串作爲NSDictionary再試)

+1

這不起作用。 NSString不響應'countByEnumeratingWithState:objects:count:'。 – sverrejoh 2012-06-27 05:46:47