开发者

Detect the number of times a word shows up in a string - iphone xcode objective-c

开发者 https://www.devze.com 2023-04-07 06:56 出处:网络
iphone xcode objective-c: I have a string with alot of text.. I want to detect how many times @\"hello\" is in the string...

iphone xcode objective-c:

I have a string with alot of text..

I want to detect how many times @"hello" is in the string...

I know how to detect if it is or is开发者_运维百科n't but how do I detect the number of times it appears in the string?


You can use regular expressions for this:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\bhello\\b" options:NSRegularExpressionCaseInsensitive error:NULL];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:someString options:0 range:NSMakeRange(0, [string length])];


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


NSRegularExpression *aRegex = [[NSRegularExpression alloc] initWithPattern:@"Hello" options:NSRegularExpressionCaseInsensitive error:nil];
NSString *targetString = @"Hello, Albert! Hello, again!";
NSInteger numberOfMatches = [aRegex numberOfMatchesInString:targetString options:0 range:NSMakeRange(0, [targetString length])];
[aRegex release];
NSLog(@"number of matches: %d", numberOfMatches); // 2

You may need to play a little with the regex.

0

精彩评论

暂无评论...
验证码 换一张
取 消