NSString中子string的出现次数?

我怎样才能得到一个NSString(例如, @"cake" )出现在一个更大的NSString(例如, @"Cheesecake, apple cake, and cherry pie" )的次数?

我需要在很多string上执行此操作,所以无论使用哪种方法,都需要相对较快。

谢谢!

这不是testing,但应该是一个好的开始。

 NSUInteger count = 0, length = [str length]; NSRange range = NSMakeRange(0, length); while(range.location != NSNotFound) { range = [str rangeOfString: @"cake" options:0 range:range]; if(range.location != NSNotFound) { range = NSMakeRange(range.location + range.length, length - (range.location + range.length)); count++; } } 

像下面的正则expression式应该做的工作没有循环交互…

编辑

 NSString *string = @"Lots of cakes, with a piece of cake."; NSError *error = NULL; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"cake" options:NSRegularExpressionCaseInsensitive error:&error]; NSUInteger numberOfMatches = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, [string length])]; NSLog(@"Found %i",numberOfMatches); 

只适用于iOS 4.x和上级。

正在寻找一个更好的方法,然后我的另一个例子:

 NSString *find = @"cake"; NSString *text = @"Cheesecake, apple cake, and cherry pie"; NSInteger strCount = [text length] - [[text stringByReplacingOccurrencesOfString:find withString:@""] length]; strCount /= [find length]; 

我想知道哪一个更有效。

而且我为了更好的使用而创build了一个NSString类别:

 // NSString+CountString.m @interface NSString (CountString) - (NSInteger)countOccurencesOfString:(NSString*)searchString; @end @implementation NSString (CountString) - (NSInteger)countOccurencesOfString:(NSString*)searchString { NSInteger strCount = [self length] - [[self stringByReplacingOccurrencesOfString:searchString withString:@""] length]; return strCount / [searchString length]; } @end 

简单地称呼它:

 [text countOccurencesOfString:find]; 

可选:您可以修改它以通过定义options:来search不区分大小写options:

有几种方法可以做到这一点。 你可以迭代地调用rangeOfString:options:range:或者你可以这样做:

 NSArray * portions = [aString componentsSeparatedByString:@"cake"]; NSUInteger cakeCount = [portions count] - 1; 

编辑我一直在想这个问题,我写了一个线性时间algorithm来做search(线性的干草堆串的长度):

 + (NSUInteger) numberOfOccurrencesOfString:(NSString *)needle inString:(NSString *)haystack { const char * rawNeedle = [needle UTF8String]; NSUInteger needleLength = strlen(rawNeedle); const char * rawHaystack = [haystack UTF8String]; NSUInteger haystackLength = strlen(rawHaystack); NSUInteger needleCount = 0; NSUInteger needleIndex = 0; for (NSUInteger index = 0; index < haystackLength; ++index) { const char thisCharacter = rawHaystack[index]; if (thisCharacter != rawNeedle[needleIndex]) { needleIndex = 0; //they don't match; reset the needle index } //resetting the needle might be the beginning of another match if (thisCharacter == rawNeedle[needleIndex]) { needleIndex++; //char match if (needleIndex >= needleLength) { needleCount++; //we completed finding the needle needleIndex = 0; } } } return needleCount; } 

键入更快,但可能效率更低的解决scheme。

 - (int)numberOfOccurencesOfSubstring:(NSString *)substring inString:(NSString*)string { NSArray *components = [string componentsSeparatedByString:substring]; return components.count-1; // Two substring will create 3 separated strings in the array. } 

这是一个作为NSString的扩展(与Matthew Flaschen的回答相同)的一个版本:

 @interface NSString (my_substr_search) - (unsigned) countOccurencesOf: (NSString *)subString; @end @implementation NSString (my_substring_search) - (unsigned) countOccurencesOf: (NSString *)subString { unsigned count = 0; unsigned myLength = [self length]; NSRange uncheckedRange = NSMakeRange(0, myLength); for(;;) { NSRange foundAtRange = [self rangeOfString:subString options:0 range:uncheckedRange]; if (foundAtRange.location == NSNotFound) return count; unsigned newLocation = NSMaxRange(foundAtRange); uncheckedRange = NSMakeRange(newLocation, myLength-newLocation); count++; } } @end <somewhere> { NSString *haystack = @"Cheesecake, apple cake, and cherry pie"; NSString *needle = @"cake"; unsigned count = [haystack countOccurencesOf: needle]; NSLog(@"found %u time%@", count, count == 1 ? @"" : @"s"); } 

如果要计算单词 ,而不仅仅是子string,则使用CFStringTokenizer 。

这里有另一个版本作为NSString的一个类别:

 -(NSUInteger) countOccurrencesOfSubstring:(NSString *) substring { if ([self length] == 0 || [substring length] == 0) return 0; NSInteger result = -1; NSRange range = NSMakeRange(0, 0); do { ++result; range = NSMakeRange(range.location + range.length, self.length - (range.location + range.length)); range = [self rangeOfString:substring options:0 range:range]; } while (range.location != NSNotFound); return result; } 

Swift解决scheme将是:

 var numberOfSubstringAppearance = 0 let length = count(text) var range: Range? = Range(start: text.startIndex, end: advance(text.startIndex, length)) while range != nil { range = text.rangeOfString(substring, options: NSStringCompareOptions.allZeros, range: range, locale: nil) if let rangeUnwrapped = range { let remainingLength = length - distance(text.startIndex, rangeUnwrapped.endIndex) range = Range(start: rangeUnwrapped.endIndex, end: advance(rangeUnwrapped.endIndex, remainingLength)) numberOfSubstringAppearance++ } } 

Matthew Flaschen的回答对我来说是一个好的开始。 这是我最终以一种方法的forms使用。 我采取了一个略有不同的方法来循环。 这已经通过传递给stringToCount和text的空string进行了testing,并且stringToCount作为文本中的第一个和/或最后一个字符出现。

我经常使用这个方法来计算传递文本中的段落(即stringToCount = @“\ r”)。

希望这个用于某人。

  - (int)countString:(NSString *)stringToCount inText:(NSString *)text{ int foundCount=0; NSRange range = NSMakeRange(0, text.length); range = [text rangeOfString:stringToCount options:NSCaseInsensitiveSearch range:range locale:nil]; while (range.location != NSNotFound) { foundCount++; range = NSMakeRange(range.location+range.length, text.length-(range.location+range.length)); range = [text rangeOfString:stringToCount options:NSCaseInsensitiveSearch range:range locale:nil]; } return foundCount; } 

示例调用假定该方法在名为myHelperClass的类中…

 int foundCount = [myHelperClass countString:@"n" inText:@"Now is the time for all good men to come to the aid of their country"]; 
 for(int i =0;i<htmlsource1.length-search.length;i++){ range = NSMakeRange(i,search.length); checker = [htmlsource1 substringWithRange:range]; if ([search isEqualToString:checker]) { count++; } } 

没有内置的方法。 我build议返回一个Cstring,并使用一个共同的Cstring风格的algorithm进行子字符计数…如果你真的需要这是快速的。

如果你想留在目标C中,这个链接可能会有所帮助。 它描述了NSString的基本子stringsearch。 如果你使用范围,调整和计数,那么你将有一个“纯粹的”客观的C解决scheme…虽然,缓慢。

 -(IBAction)search:(id)sender{ int maincount = 0; for (int i=0; i<[self.txtfmainStr.text length]; i++) { char c =[self.substr.text characterAtIndex:0]; char cMain =[self.txtfmainStr.text characterAtIndex:i]; if (c == cMain) { int k=i; int count=0; for (int j = 0; j<[self.substr.text length]; j++) { if (k ==[self.txtfmainStr.text length]) { break; } if ([self.txtfmainStr.text characterAtIndex:k]==[self.substr.text characterAtIndex:j]) { count++; } if (count==[self.substr.text length]) { maincount++; } k++; } } NSLog(@"%d",maincount); } }