简体   繁体   English

如何比较两个不区分大小写的字符串?

[英]How to compare two case insensitive strings?

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... 我有2个字符串对象包含相同的字符串但情况不同,现在我想比较它们忽略区分大小写,怎么做?这里是代码...

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

If you look up caseInsensitiveCompare: in the docs you'll see that it returns an NSComparisonResult rather than a BOOL. 如果你查找caseInsensitiveCompare: 在文档中你会看到它返回一个NSComparisonResult而不是BOOL。 Look that up in the docs and you'll see that you probably want it to be NSOrderedSame. 在文档中查找,你会发现你可能希望它是NSOrderedSame。 So 所以

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

should do the trick. 应该做的伎俩。 Or just compare the lowercase strings like Robert suggested. 或者只是比较罗伯特建议的小写字符串。

Just use lowercaseString on both of the strings and then compare them as you would using a normal string equality check. 只需在两个字符串上使用lowercaseString,然后像使用普通字符串相等性检查一样比较它们。 It will still be O(n) so no big deal. 它仍然是O(n)所以没什么大不了的。

I would rather suggest to add a category on NSString: 我宁愿建议在NSString上添加一个类别:

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

With this you can simply call: 有了这个你可以简单地打电话:

[myString1 isEqualIgnoreCaseToString:myString2];

To save a method call, I used a macro via a #define : 为了保存方法调用,我通过#define使用了一个宏:

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

Then call: 然后打电话:

(BOOL) option = isEqualIgnoreCaseToString(compareString, toString);

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM