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?
Use the option NSCaseInsensitiveSearch with rangeOfString:options:
Output result is found:Yes
The options can be "or'ed" together and include:
NSCaseInsensitiveSearch NSLiteralSearch NSBackwardsSearch and more
NOTE: This answer is now obsolete
Create a category for NSString:
EDIT: Observe Daniel Galasko's comment below regarding naming
If you need this once write:
SWift 4 And Above
Oneliner (Smaller amount of code. DRY, as you have only one
NSLog
):So personally I really hate
NSNotFound
but understand its necessity.But some people may not understand the complexities of comparing against NSNotFound
For example, this code:
has its problems:
1) Obviously if
otherString = nil
this code will crash. a simple test would be:results in !! CRASH !!
2) What is not so obvious to someone new to objective-c is that the same code will NOT crash when
string = nil
. For example, this code:and this code:
will both result in
Which is clearly NOT what you want.
So the better solution that I believe works is to use the fact that rangeOfString returns the length of 0 so then a better more reliable code is this:
OR SIMPLY:
which will for cases 1 and 2 will return
That's my 2 cents ;-)
Please check out my Gist for more helpful code.