IPhone Objective-C: If the line contains ...?

How do I know if a string contains something? Sort of:

if([someTextField.text containsString:@"hello"]) { } 
+4
source share
3 answers

You can use:

 if ( result && [result rangeOfString:@"hello"].location != NSNotFound ) { // Substring found... } 
+22
source

You should use - (NSRange)rangeOfString:(NSString *)aString

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

Read more here: NSString rangeOfString

+7
source

If the goal of your code is to check if a string contains another string, you can create a category to make this intention 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 you may need to modify it a bit.

Quentin

+2
source

All Articles