Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a string contains another string in Objective-C?

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?

like image 619
Jonathan. Avatar asked May 02 '10 15:05

Jonathan.


People also ask

How do you check if a string contains part of 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.

How do you check if a string matches another string in C?

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.

Does one string contain another Swift?

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.

How do you check if a string contains a phrase?

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.


1 Answers

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)

👍

like image 51
Dave DeLong Avatar answered Sep 21 '22 06:09

Dave DeLong