views:

202

answers:

4

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

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

}
+5  A: 

You could use:

[text rangeOfString:@"hello"].location != NSNotFound
mvds
+1  A: 

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
In what Universe is that answer "a little bit tricky"?
JeremyP
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
vodkhang
A: 

IF you need the count of occurrences of the string you can also do

int stringCount = 0;
NSArray *parts = [myStr componentsSeparatedByString:@"hello"];
if ([parts count] > 1) {
    stringCount = partsCount - 1;
}
return stringCount;
Andrei Freeman
A: 

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