How can I check if a string (NSString
) contains another smaller string?
I was hoping for something like:
NSString *string = @"hello bla bla";
NSLog(@"%d",[string containsSubstring:@"hello"]);
But the closest I could find was:
if ([string rangeOfString:@"hello"] == 0) {
NSLog(@"sub string doesnt exist");
}
else {
NSLog(@"exists");
}
Anyway, is that the best way to find if a string contains another string?
Please use this code
Since this seems to be a high-ranking result in Google, I want to add this:
iOS 8 and OS X 10.10 add the
containsString:
method toNSString
. An updated version of Dave DeLong's example for those systems:An improved version of P i's solution, a category on NSString, that not only will tell, if a string is found within another string, but also takes a range by reference, is:
Use it like:
try this,
In case of swift, this can be used