Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search if NSString contains value

Tags:

objective-c

I have some string value which constructed from a few characters , and i want to check if they exist in another NSString, without case sensitive, and spaces .

Example code :

NSString *me = @"toBe" ;
NSString *target=@"abcdetoBe" ;
//than check if me is in target.

Here i will get true because me exist in target . How can i check for such condition ?

I have read How do I check if a string contains another string in Objective-C? but its case sensitive and i need to find with no case sensitive..

like image 237
Curnelious Avatar asked Feb 23 '14 13:02

Curnelious


3 Answers

Use the option NSCaseInsensitiveSearch with rangeOfString:options:

NSString *me = @"toBe" ;
NSString *target = @"abcdetobe" ;
NSRange range = [target  rangeOfString: me options: NSCaseInsensitiveSearch];
NSLog(@"found: %@", (range.location != NSNotFound) ? @"Yes" : @"No");
if (range.location != NSNotFound) {
    // your code
}

NSLog output:

found: Yes

Note: I changed the target to demonstrate that case insensitive search works.

The options can be "or'ed" together and include:

  • NSCaseInsensitiveSearch
  • NSLiteralSearch
  • NSBackwardsSearch
  • NSAnchoredSearch
  • NSNumericSearch
  • NSDiacriticInsensitiveSearch
  • NSWidthInsensitiveSearch
  • NSForcedOrderingSearch
  • NSRegularExpressionSearch
like image 172
zaph Avatar answered Nov 15 '22 07:11

zaph


-(BOOL)substring:(NSString *)substr existsInString:(NSString *)str {
    if(!([str rangeOfString:substr options:NSCaseInsensitiveSearch].length==0)) {
        return YES;
    }

    return NO;
}

usage:

NSString *me = @"toBe";
NSString *target=@"abcdetoBe";
if([self substring:me existsInString:target]) {
    NSLog(@"It exists!");
}
else {
    NSLog(@"It does not exist!");
}
like image 40
Jonathan Gurebo Avatar answered Nov 15 '22 08:11

Jonathan Gurebo


As with the release of iOS8, Apple added a new method to NSStringcalled localizedCaseInsensitiveContainsString. This will exactly do what you want:

Swift:

let string: NSString = "ToSearchFor"
let substring: NSString = "earch"

string.localizedCaseInsensitiveContainsString(substring) // true

Objective-C:

NSString *string = @"ToSearchFor";
NSString *substring = @"earch";

[string localizedCaseInsensitiveContainsString:substring]; //true
like image 22
Alexander Avatar answered Nov 15 '22 09:11

Alexander