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?
Best Solution
The key is noticing that
rangeOfString:
returns anNSRange
struct, and the documentation says that it returns the struct{NSNotFound, 0}
if the "haystack" does not contain the "needle".And if you're on iOS 8 or OS X Yosemite, you can now do: (*NOTE: This WILL crash your app if this code is called on an iOS7 device).
(This is also how it would work in Swift)
👍