簡體   English   中英

如何計算NSString中NSString的數量

[英]How to count the number of NSString in a NSString

您好,我嘗試在iPhone的Objective-C中轉換我的Java函數

Java:

    public int substrCount(String str, String needle) {
    int count = 0;
    int index = -needle.length();
    while ((index = str.indexOf(needle, index + needle.length())) != -1) {
        count++;
    }
    return count;
}

蘋果手機:

-(int)substrCount:(NSString *) str withSearch:(NSString *) needle
{
  NSRange lastIndex;
  lastIndex.length = [str length];
  NSInteger count =0;

  while(lastIndex.length != -1){
    lastIndex = [str rangeOfString:needle options:NSCaseInsensitiveSearch range:lastIndex];
    //lastIndex = str.indexOf(needle,lastIndex);

    if( lastIndex.length != -1){
        NSLog(@"+1");
        count ++;
    }
  }
}

但這太難了,我不知道什么時候能做到。

也許有更好的解決方案? 我什么都沒找到:/

對不起,我的英語不好 !

我可能永遠不會在生產中編寫此代碼,但是您可以問一下:

[[str1 componentsSeparatedByString:str2] count]-1;

該表達式的結果將是表示次數的整數str2在發現str1

但是,代碼的問題是rangeOfString:如果找不到子字符串,則返回NSNotFound ,而不是-1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM