4

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

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

}
2
  • there's nothing wrong to minus here:) Commented Aug 3, 2010 at 1:03
  • Same as [ String contains string in objective-c (iphone) ](stackoverflow.com/questions/2753956/…). Commented Aug 3, 2010 at 1:04

3 Answers 3

22

You could use:

if ( result && [result rangeOfString:@"hello"].location != NSNotFound ) {
    // Substring found...
}
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

In what Universe is that answer "a little bit tricky"?
Because for me, from the background of java. We should use [str contains:], so when I discovered the API, it looks a little bit strange. I think the questioner think the same so I say a little bit tricky
hahahaha Jeremy's post just made me lol
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.