34

My question is similar to How do I check if a string contains another string in Objective-C?

How can I check if a string (NSString) contains another smaller string but with ignoring case?

NSString *string = @"hello bla bla";

I was hoping for something like:

NSLog(@"%d",[string containsSubstring:@"BLA"]);

Anyway is there any way to find if a string contains another string with ignore case ? But please do not convert both strings to UpperCase or to LowerCase.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Jim
  • 8,874
  • 16
  • 68
  • 125

6 Answers6

87

As similar to the answer provided in the link, but use options.

See - (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask in Apple doc

NSString *string = @"hello bla bla";

if ([string rangeOfString:@"BLA" options:NSCaseInsensitiveSearch].location == NSNotFound)
{
    NSLog(@"string does not contain bla");
} 
else 
{
    NSLog(@"string contains bla!");
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Ilanchezhian
  • 17,426
  • 1
  • 53
  • 55
16

From iOS 8 you can add the containsString: or localizedCaseInsensitiveContainsString method to NSString.

if ([string localizedCaseInsensitiveContainsString:@"BlA"]) {
    NSLog(@"string contains Case Insensitive bla!");
} else {
    NSLog(@"string does not contain bla");
}
ajay_nasa
  • 2,278
  • 2
  • 28
  • 45
3
NSString *string = @"hello BLA";
if ([string rangeOfString:@"bla" options:NSCaseInsensitiveSearch].location == NSNotFound) {
    NSLog(@"string does not contain bla");
} else {
    NSLog(@"string contains bla!");
}
Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184
0

For Swift 4:

extension String {
    func containsCaseInsensitive(string : String) -> Bool {
        return self.localizedCaseInsensitiveContains(string)
    }
}

Usage:

print("Hello".containsCaseInsensitive(string: "LLO"))

Output:

true
Cristik
  • 30,989
  • 25
  • 91
  • 127
Md. Ibrahim Hassan
  • 5,359
  • 1
  • 25
  • 45
0

The method

[string rangeOfString:@"bla" options:NSCaseInsensitiveSearch];

should help you.

Pierre
  • 2,019
  • 14
  • 12
0

You can use -(NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask; to get a range for a substring, the mask parameter is used to specify case insensitive match.

Example :

NSRange r = [str rangeOfString:@"BLA"
                       options:NSCaseInsensitiveSearch];

As stated in the documentation, the method returns a range like {NSNotFound, 0} when the substring isn't found.

BOOL b = r.location == NSNotFound;

Important this method raises an exception if the string is nil.