How can I check if a string (NSString
) contains another smaller string?
I was hoping for something like:
NSString *string = @\"hello bla
Please use this code
NSString *string = @"hello bla bla";
if ([string rangeOfString:@"bla"].location == NSNotFound)
{
NSLog(@"string does not contain bla");
}
else
{
NSLog(@"string contains bla!");
}
Here is a copy-and-paste function snippet:
-(BOOL)Contains:(NSString *)StrSearchTerm on:(NSString *)StrText
{
return [StrText rangeOfString:StrSearchTerm
options:NSCaseInsensitiveSearch].location != NSNotFound;
}
In case of swift, this can be used
let string = "Package #23"
if string.containsString("Package #") {
//String contains substring
}
else {
//String does not contain substring
}
With iOS 8 and Swift, we can use localizedCaseInsensitiveContainsString
method
let string: NSString = "Café"
let substring: NSString = "É"
string.localizedCaseInsensitiveContainsString(substring) // true
If you need this once write:
NSString *stringToSearchThrough = @"-rangeOfString method finds and returns the range of the first occurrence of a given string within the receiver.";
BOOL contains = [stringToSearchThrough rangeOfString:@"occurence of a given string"].location != NSNotFound;