2011-11-23 71 views
3

我有一個NSString,我想找到它中的空格數。什麼是最快的方式?找到NSString中空格的最快方法是什麼?

+1

基本上與[計數行](http://stackoverflow.com/q/1287145/30461)相同的問題,只是沒有支持多行分隔符的摺痕。 –

回答

0

我還沒有測試過這個,但它好像應該在我頭頂上工作。

int spacesCount = 0; 

NSRange textRange; 
textRange = [string rangeOfString:@" "]; 

if(textRange.location != NSNotFound) 
{ 
    spacesCount = spacesCount++; 
} 

NSLog(@"Spaces Count: %i", spacesCount); 
+4

你是不是錯過了一個循環?.. – dasblinkenlight

3

也許不是最快的執行,而是以最快的速度輸入了:

[[myString componentsSeparatedByString:@" "] count]-1 
+0

如果有兩個或更多的連續空間怎麼辦? – SSteve

+0

根據[NSString文檔](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html),「相鄰的分隔符字符串產生結果中的空字符串「。 – dasblinkenlight

+0

你是對的。你的解決方案比我的優雅得多。 Upvoting。 – SSteve

1

我嘗試這樣做,它似乎工作。優化可能是可能的,但如果這是絕對必要的,你只需要擔心。

NSUInteger spacesInString(NSString *theString) { 
    NSUInteger result = 0; 
    if ([theString length]) { 
     const char *utfString = [theString UTF8String]; 
     NSUInteger i = 0; 
     while (utfString[i]) { 
      if (' ' == utfString[i]) { 
       result++; 
      } 
      i++; 
     } 
    } 

    return result; 
} 
相關問題