How to compare two case insensitive strings?

房东的猫 提交于 2019-12-01 04:36:41

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.

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.

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];
Mike M.

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);

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!