How to compare two case insensitive strings?

2020-03-19 07:29发布

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...

#import <Foundation/Foundation.h>
void main()  
{  
    NSString *myString1 = @"mphasis";  
    NSString *myString2 = @"MPHASIS";
    if ([myString1 caseInsenstiveCompare:myString2])  
    {  
        NSLog (@"ITS EQUAL");  
    }  
    else  
    {   
        NSLog (@"ITS NOT EQUAL");  
    }  
}  

5条回答
Rolldiameter
2楼-- · 2020-03-19 07:40

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.

查看更多
Explosion°爆炸
3楼-- · 2020-03-19 07:46

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.

查看更多
放荡不羁爱自由
4楼-- · 2020-03-19 07:50

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);
查看更多
【Aperson】
5楼-- · 2020-03-19 07:57

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
}
查看更多
做自己的国王
6楼-- · 2020-03-19 08:05

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];
查看更多
登录 后发表回答