NSString : number of a word [duplicate]
Possible Duplicate:
Number of occurrences of a substring in an NSString?
I would like to know if there's a method which returns the occurrence of a given word.
NSString *string = @"ok no ok no no no ok";
// How to return 4 for the word no ?
Thanks for you开发者_开发问答r help !
use this API: - (NSArray *)componentsSeparatedByString:(NSString *)separator
NSString* stringToSearch = @"ok no ok no no no ok";
NSString* stringToFind = @"no";
NSArray *listItems = [list componentsSeparatedByString:stringToFind];
int count = [listItems count] - 1;
You will get number of occurences of string @"no" in "count" variable
If you are writing a 10.5+ only application, you should be able to use NSString's stringByReplacingOccurrencesOfString:withString:
method to do this with fairly minimal code, by checking the length before and after removing the string you're searching for.
Example below (untested as I'm working on 10.4, but can't see why it wouldn't work.) I wouldn't make your application 10.5+ only just to use this though, plenty of other methods suggested by Macmade and in the duplicate question.
NSString* stringToSearch = @"ok no ok no no no ok";
NSString* stringToFind = @"no";
int lengthBefore, lengthAfter, count;
lengthBefore = [stringToSearch length];
lengthAfter = [[stringToSearch stringByReplacingOccurrencesOfString:stringToFind withString:@""] length];
count = (lengthBefore - lengthAfter) / [stringToFind length];
NSLog(@"Found the word %i times", count);
You want to use an NSScanner for this sort of activity.
NSString *string = @"ok no ok no no no ok";
NSScanner *theScanner;
NSString *TARGET = @"no"; // careful selecting target string this would detect no in none as well
int count = 0;
theScanner = [NSScanner scannerWithString:string];
while ([theScanner isAtEnd] == NO)
{
if ([theScanner scanString:TARGET intoString:NULL] )
count++;
}
NSLog(@"target (%@) occurrences = %d", TARGET, count)
;
May not be the fastest way, but you can use the NSString componentsSeparatedByString method to separate your values into an array, and then work with that array to check how many times the string 'no' is contained...
Otherwise, work on a C string ptr, and loop, incrementing the ptr, while using strncmp() or so...
精彩评论