string 不区分大小写的 NSString 比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4488877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Case-insensitive NSString comparison
提问by user198725878
Using this code I am able to compare string values.
使用此代码,我可以比较字符串值。
[elementName isEqualToString: @"Response"]
But this compares case-sensitively. Is there a way to compare the string without case sensitivity?
但这比较区分大小写。有没有办法在不区分大小写的情况下比较字符串?
回答by zoul
There's a caseInsensitiveCompare:
method on NSString
, why don't you read the?documentation? The method returns NSComparisonResult
:
有一个caseInsensitiveCompare:
方法NSString
,你为什么不阅读?文档?该方法返回NSComparisonResult
:
enum {
NSOrderedAscending = -1,
NSOrderedSame,
NSOrderedDescending
};
typedef NSInteger NSComparisonResult;
…ah, sorry, just now I realized you are asking for case sensitiveequality. (Why don't I?read the question? :-) The default isEqual:
or isEqualToString:
equality should already be case sensitive, what gives?
……啊,抱歉,刚刚我意识到您要求区分大小写的平等。(为什么我不读这个问题?:-) 默认isEqual:
或isEqualToString:
相等应该已经区分大小写了,是什么给出了?
回答by Mike Gledhill
Here's the code you would need to compare a string without caring about whether it's lowercase or uppercase:
这是您需要比较字符串而不关心它是小写还是大写的代码:
if ([elementName caseInsensitiveCompare:@"Response"]==NSOrderedSame)
{
// Your "elementName" variable IS "Response", "response", "reSPonse", etc
//
}
回答by iPhoneDv
Actually isEqualToString: works with case sensitive ability. as:
实际上 isEqualToString: 具有区分大小写的能力。作为:
[elementName isEqualToString: @"Response"];
if you want to ask for case insensitive compare then here is the code:
如果你想要求不区分大小写的比较,那么这里是代码:
You can change both comparable string to lowerCase or uppercase, and can compare as:
您可以将两个可比较的字符串更改为小写或大写,并且可以比较为:
NSString *tempString = @"Response";
NSString *string1 = [elementName lowercaseString];
NSString *string2 = [tempString lowercaseString];
//The same code changes both strings in lowerCase.
//Now You Can compare
if([string1 isEqualToString:string2])
{
//Type your code here
}
回答by Amr Lotfy
NSString *string1 = @"stringABC";
NSString *string2 = @"STRINGDEF";
NSComparisonResult result = [string1 caseInsensitiveCompare:string2];
if (result == NSOrderedAscending) {
NSLog(@"string1 comes before string2");
} else if (result == NSOrderedSame) {
NSLog(@"We're comparing the same string");
} else if (result == NSOrderedDescending) {
NSLog(@"string2 comes before string1");
}