How can I check if a string (NSString
) contains another smaller string?
I was hoping for something like:
NSString *string = @\"hello bla
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");
}
Swift 4 And Above
let str = "Hello iam midhun"
if str.contains("iam") {
//contains substring
}
else {
//doesn't contain substring
}
Objective-C
NSString *stringData = @"Hello iam midhun";
if ([stringData containsString:@"iam"]) {
//contains substring
}
else {
//doesn't contain substring
}
Try this:
Swift 4.1 , 4.2:
let stringData = "Black board"
//swift quick way and case sensitive
if stringData.contains("bla") {
print("data contains string");
}
//case sensitive
if stringData.range(of: "bla",options: .caseInsensitive) != nil {
print("data contains string");
}else {
print("data does not contains string");
}
For Objective-C:
NSString *stringData = @"Black board";
//Quick way and case sensitive
if ([stringData containsString:@"bla"]) {
NSLog(@"data contains string");
}
//Case Insensitive
if ([stringData rangeOfString:@"bla" options:NSCaseInsensitiveSearch].location != NSNotFound) {
NSLog(@"data contains string");
}else {
NSLog(@"data does not contain string");
}
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
NSString *categoryString = @"Holiday Event";
if([categoryString rangeOfString:@"Holiday"].location == NSNotFound)
{
//categoryString does not contains Holiday
}
else
{
//categoryString contains Holiday
}
If certain position of the string is needed, this code comes to place in Swift 3.0:
let string = "This is my string"
let substring = "my"
let position = string.range(of: substring)?.lowerBound