How can I tell if a string contains something? Something like:
if([someTextField.text containsString:@"hello"]) {
}
How can I tell if a string contains something? Something like:
if([someTextField.text containsString:@"hello"]) {
}
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
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;
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