views:

352

answers:

4

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 your help !

+1  A: 

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...

Macmade
What's with you and the C string library? ;) NSString is a lot simpler to work with in the context of Obj-C.
Williham Totland
lol ; ) IMHO, it depends on what you want to achieve, and if you need performance over ease of use...
Macmade
I need performance, it must be very fast.
Pierre
If that's true, then yes, get at the C string and write your own loop to do the compare character by character (or with strncmp). That'll be about the best you can do.
quixoto
+1  A: 

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);
wipolar
A: 

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)

;

Chip Coons
+2  A: 

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

Manjunath
Brilliant answer, appreciated!
Raj