NSString search whole text for another string
I would like to search for an NSString in another NSString, such that the result is found even if the second one does not start with the first one, for example:
eg: I have a search string "st". I look in the following records to see if any of the below contains this search string, all of them should return a good result, because all of them have "st".
Restaurant
stable
Kirsten
At the moment I am doing the following:
NSComparisonResult result = [selectedString compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
This works only for "stable" in the above example, because it starts with "st" and fails for the other 2. How can I modify 开发者_Python百科this search so that it returns ok for all the 3?
Thanks!!!
Why not google first?
String contains 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!");
}
Compare is used for testing less than/equal/greater than. You should instead use -rangeOfString:
or one of its sibling methods like -rangeOfString:options:range:locale:
.
I know this is an old thread thought it might help someone.
The - rangeOfString:options:range:
method will allow for case insensitive searches on a string and replace letters like ‘ö’ to ‘o’ in your search.
NSString *string = @"Hello Bla Bla";
NSString *searchText = @"bla";
NSUInteger searchOptions = NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch;
NSRange searchRange = NSMakeRange(0, string.length);
NSRange foundRange = [string rangeOfString:searchText options:searchOptions range:searchRange];
if (foundRange.length > 0) {
NSLog(@"Text Found.");
}
For more comparison options NSString Class Reference
Documentation on the method - rangeOfString:options:range:
can be found on the NSString Class Reference
精彩评论