4

How can I tell if a string contains something? Something like:

if([someTextField.text containsString:@"hello"]) {

}
Bob
  • 51
  • 1
  • 1
  • 2

3 Answers3

22

You could use:

if ( result && [result rangeOfString:@"hello"].location != NSNotFound ) {
    // Substring found...
}
mvds
  • 43,261
  • 8
  • 96
  • 109
7

You have to use - (NSRange)rangeOfString:(NSString *)aString

NSRange range = [myStr rangeOfString:@"hello"];
if (range.location != NSNotFound) {
  NSLog (@"Substring found at: %d", range.location);
}

View more here: NSString rangeOfString

vodkhang
  • 18,281
  • 10
  • 73
  • 109
2

If the intent of your code is to check if a string contains another string you can create a category to make this intent clear.

@interface NSString (additions)

- (BOOL)containsString:(NSString *)subString;

@end

@implementation NSString (additions)

- (BOOL)containsString:(NSString *)subString {
    BOOL containsString = NO;

    NSRange range = [self rangeOfString:subString];
    if (range.location != NSNotFound) {
        containsString = YES;
    }

    return containsString;
}

@end

I have not compiled this code, so maybe you should have to change it a bit.

Quentin

Quentin
  • 1,611
  • 2
  • 17
  • 27