How to compare two case insensitive strings?

前端 未结 5 360
鱼传尺愫
鱼传尺愫 2021-01-12 17:00

i have 2 string objects containing same string but case is different,now i wanna compare them ignoring the case sensitivity,how to do that??here is the code...



        
相关标签:
5条回答
  • 2021-01-12 17:32

    Just use lowercaseString on both of the strings and then compare them as you would using a normal string equality check. It will still be O(n) so no big deal.

    0 讨论(0)
  • 2021-01-12 17:38

    A simple one, convert both strings in same case.Here i'm converting it to lower case and then checking it.

    if ([[myString1 lowercaseString] [myString2 lowercaseString]])
    {
     // same
    }
    
    0 讨论(0)
  • 2021-01-12 17:47

    To save a method call, I used a macro via a #define:

    #define isEqualIgnoreCaseToString(string1, string2) ([string1 caseInsensitiveCompare:string2] == NSOrderedSame)
    

    Then call:

    (BOOL) option = isEqualIgnoreCaseToString(compareString, toString);
    
    0 讨论(0)
  • 2021-01-12 17:51

    I would rather suggest to add a category on NSString:

    - (BOOL)isEqualIgnoreCaseToString:(NSString *)iString {
        return ([self caseInsensitiveCompare:iString] == NSOrderedSame);
    }
    

    With this you can simply call:

    [myString1 isEqualIgnoreCaseToString:myString2];
    
    0 讨论(0)
  • 2021-01-12 17:53

    If you look up caseInsensitiveCompare: in the docs you'll see that it returns an NSComparisonResult rather than a BOOL. Look that up in the docs and you'll see that you probably want it to be NSOrderedSame. So

    if ([myString1 caseInsensitiveCompare:myString2] == NSOrderedSame)

    should do the trick. Or just compare the lowercase strings like Robert suggested.

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