Case insensitive comparison NSString

后端 未结 12 1597
滥情空心
滥情空心 2020-12-12 13:15

Can anyone point me to any resources about case insensitive comparison in Objective C? It doesn\'t seem to have an equivalent method to str1.equalsIgnoreCase(str2)

相关标签:
12条回答
  • 2020-12-12 13:51

    Converting Jason Coco's answer to Swift for the profoundly lazy :)

    if ("Some String" .caseInsensitiveCompare("some string") == .OrderedSame)
    {
      // Strings are equal.
    }
    
    0 讨论(0)
  • 2020-12-12 13:53
    - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString
    
    0 讨论(0)
  • 2020-12-12 13:55
     NSString *stringA;
     NSString *stringB;
    
     if (stringA && [stringA caseInsensitiveCompare:stringB] == NSOrderedSame) {
         // match
     }
    

    Note: stringA && is required because when stringA is nil:

     stringA = nil;
     [stringA caseInsensitiveCompare:stringB] // return 0
    

    and so happens NSOrderedSame is also defined as 0.

    The following example is a typical pitfall:

     NSString *rank = [[NSUserDefaults standardUserDefaults] stringForKey:@"Rank"];
     if ([rank caseInsensitiveCompare:@"MANAGER"] == NSOrderedSame) {
         // what happens if "Rank" is not found in standardUserDefaults
     }
    
    0 讨论(0)
  • 2020-12-12 14:00

    On macOS you can simply use -[NSString isCaseInsensitiveLike:], which returns BOOL just like -isEqual:.

    if ([@"Test" isCaseInsensitiveLike: @"test"])
        // Success
    
    0 讨论(0)
  • 2020-12-12 14:01

    Alternate solution for swift:

    To make both UpperCase:

    e.g:

    if ("ABcd".uppercased() == "abcD".uppercased()){
    }
    

    or to make both LowerCase:

    e.g:

    if ("ABcd".lowercased() == "abcD".lowercased()){
    }
    
    0 讨论(0)
  • 2020-12-12 14:03

    An alternative if you want more control than just case insensitivity is:

    [someString compare:otherString options:NSCaseInsensitiveSearch];
    

    Numeric search and diacritical insensitivity are two handy options.

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