Check for a word in NSString

I searched a little, but could not find the answer to this (possibly very simple) question.

I have an NSString and I want to check if it contains a word. Something like that:

NSString *sentence = @"The quick brown fox";
NSString *word = @"quack";
if ([sentence containsWord:word]) {
    NSLog(@"Yes it does contain that word");
}

Thanks.

+3
source share
1 answer

The following should work:

NSString *sentence = @"The quick brown fox";
NSString *word = @"quack";
if ([sentence rangeOfString:word].location != NSNotFound) {
    NSLog(@"Yes it does contain that word");
}

He uses rangeOfString:to return a structure NSRangeindicating the location of the word, if he can not find it NSRange.locationwill be equal NSNotFound.

+21
source

Source: https://habr.com/ru/post/1720342/


All Articles