iphone xcode objective-c:
我有一个包含大量文字的字符串..
我想检测@“hello”在字符串中的次数...
我知道如何检测它是否存在,但我如何检测它在字符串中出现的次数?
答案 0 :(得分:4)
您可以使用正则表达式:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\bhello\\b" options:NSRegularExpressionCaseInsensitive error:NULL];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:someString options:0 range:NSMakeRange(0, [string length])];
答案 1 :(得分:2)
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++;
}
}
答案 2 :(得分:0)
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
您可能需要使用正则表达式进行一些操作。