2

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!!!

user542584
  • 2,231
  • 2
  • 23
  • 29

3 Answers3

11

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!");
}
Community
  • 1
  • 1
d.lebedev
  • 2,285
  • 17
  • 27
  • Thanks for all the answers, I did try googling, but somehow did not get the correct search term and it was not coming up with valid answers..also searched documentation, but yes I accept that I should have tried harder. – user542584 Sep 27 '11 at 20:24
1

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

1

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

Jeremy W. Sherman
  • 34,925
  • 5
  • 73
  • 108