Find one string in another with case insensitive in Objective-C

后端 未结 5 2123
慢半拍i
慢半拍i 2021-02-11 17:24

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 w

相关标签:
5条回答
  • 2021-02-11 17:43

    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");
    }
    
    0 讨论(0)
  • 2021-02-11 17:49
    NSString *string = @"hello BLA";
    if ([string rangeOfString:@"bla" options:NSCaseInsensitiveSearch].location == NSNotFound) {
        NSLog(@"string does not contain bla");
    } else {
        NSLog(@"string contains bla!");
    }
    
    0 讨论(0)
  • 2021-02-11 17:52

    The method

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

    should help you.

    0 讨论(0)
  • 2021-02-11 17:55

    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!");
    }
    
    0 讨论(0)
  • 2021-02-11 18:00

    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.

    0 讨论(0)
提交回复
热议问题