How do I check if a string contains another string in Objective-C?
NSString *string = @"hello bla bla";
if ([string rangeOfString:@"bla"].location == NSNotFound) {
NSLog(@"string does not contain bla");
} else {
NSLog(@"string contains bla!");
}
The key is noticing that rangeOfString:
returns an NSRange
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).
NSString *string = @"hello bla blah";
if ([string containsString:@"bla"]) {
NSLog(@"string contains bla!");
} else {
NSLog(@"string does not contain bla");
}
(This is also how it would work in Swift)
ð
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 to NSString
. An updated version of Dave DeLong's example for those systems:
NSString *string = @"hello bla bla";
if ([string containsString:@"bla"]) {
NSLog(@"string contains bla!");
} else {
NSLog(@"string does not contain bla");
}
NSString *myString = @"hello bla bla";
NSRange rangeValue = [myString rangeOfString:@"hello" options:NSCaseInsensitiveSearch];
if (rangeValue.length > 0)
{
NSLog(@"string contains hello");
}
else
{
NSLog(@"string does not contain hello!");
}
//You can alternatively use following too :
if (rangeValue.location == NSNotFound)
{
NSLog(@"string does not contain hello");
}
else
{
NSLog(@"string contains hello!");
}
For iOS 8.0+ and macOS 10.10+, you can use NSString's native containsString:
.
For older versions of iOS and macOS, you can create your own (obsolete) category for NSString:
@interface NSString ( SubstringSearch )
- (BOOL)containsString:(NSString *)substring;
@end
// - - - -
@implementation NSString ( SubstringSearch )
- (BOOL)containsString:(NSString *)substring
{
NSRange range = [self rangeOfString : substring];
BOOL found = ( range.location != NSNotFound );
return found;
}
@end
Note: Observe Daniel Galasko's comment below regarding naming