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?
You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.
We take the user input as strings. We compare the strings by using the strcmp() function, i.e., strcmp(str1,str2). This function will compare both the strings str1 and str2. If the function returns 0 value means that both the strings are same, otherwise the strings are not equal.
Swift provides ways to check if a string contains another string, numbers, uppercased/lowercased string, or special characters. Each scenario might need a different method.
You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false . Also note that string positions start at 0, and not 1.
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)
👍
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With