Detecting if an NSString contains...?

How can I detect if a string contains a certain word? For example, I have a string below which reads:

@"Here is my string."

I'd like to know if I can detect a word in the string, such as "is" for example.


Solution 1:

Here's how I would do it:

NSString *someString = @"Here is my string";
NSRange isRange = [someString rangeOfString:@"is " options:NSCaseInsensitiveSearch];
if(isRange.location == 0) {
   //found it...
} else {
   NSRange isSpacedRange = [someString rangeOfString:@" is " options:NSCaseInsensitiveSearch];
   if(isSpacedRange.location != NSNotFound) {
      //found it...
   }
}

You can easily add this as a category onto NSString:

@interface NSString (JRStringAdditions) 

- (BOOL)containsString:(NSString *)string;
- (BOOL)containsString:(NSString *)string
               options:(NSStringCompareOptions)options;

@end

@implementation NSString (JRStringAdditions) 

- (BOOL)containsString:(NSString *)string
               options:(NSStringCompareOptions)options {
   NSRange rng = [self rangeOfString:string options:options];
   return rng.location != NSNotFound;
}

- (BOOL)containsString:(NSString *)string {
   return [self containsString:string options:0];
}

@end

Solution 2:

Use the following code to scan the word in sentence.

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