Search if NSString contains a value

I have a string value that is built from several characters and I want to check if they exist in another NSString, case insensitive and spaces.

Code example:

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

Here I get true, because it meexists in target. How can I check such a condition?

I read How to check if a string contains another string in Objective-C? but its case sensitive and I need to find case insensitive.

+4
source share
3 answers

Use option NSCaseInsensitiveSearchwithrangeOfString: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 goal to demonstrate that case insensitive search works.

"or'ed" :

  • NSCaseInsensitiveSearch
  • NSLiteralSearch
  • NSBackwardsSearch
  • NSAnchoredSearch
  • NSNumericSearch
  • NSDiacriticInsensitiveSearch
  • NSWidthInsensitiveSearch
  • NSForcedOrderingSearch
  • NSRegularExpressionSearch
+20
-(BOOL)substring:(NSString *)substr existsInString:(NSString *)str {
    if(!([str rangeOfString:substr options:NSCaseInsensitiveSearch].length==0)) {
        return YES;
    }

    return NO;
}

:

NSString *me = @"toBe";
NSString *target=@"abcdetoBe";
if([self substring:me existsInString:target]) {
    NSLog(@"It exists!");
}
else {
    NSLog(@"It does not exist!");
}
+2

As with iOS8, Apple has added a new method NSStringcalled localizedCaseInsensitiveContainsString. This will definitely 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
+1
source

All Articles