NSString search whole text for another string

那年仲夏 提交于 2019-12-04 05:27:36

问题


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 this search so that it returns ok for all the 3?

Thanks!!!


回答1:


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!");
}



回答2:


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:.




回答3:


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



来源:https://stackoverflow.com/questions/7574041/nsstring-search-whole-text-for-another-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!