Detecting if an NSString contains...?

Alex picture Alex · Jul 20, 2010 · Viewed 77.9k times · Source

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.

Answer

Jacob Relkin picture Jacob Relkin · Jul 20, 2010

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