Case-insensitive NSString comparison

て烟熏妆下的殇ゞ 提交于 2019-12-03 12:45:40

问题


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?


回答1:


There’s a caseInsensitiveCompare: method on NSString, why don’t you read the documentation? The method returns NSComparisonResult:

enum {
   NSOrderedAscending = -1,
   NSOrderedSame,
   NSOrderedDescending
};
typedef NSInteger NSComparisonResult;

…ah, sorry, just now I realized you are asking for case sensitive equality. (Why don’t I read the question? :-) The default isEqual: or isEqualToString: equality should already be case sensitive, what gives?




回答2:


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
    //  
}



回答3:


Actually isEqualToString: works with case sensitive ability. as:

[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

}



回答4:


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


来源:https://stackoverflow.com/questions/4488877/case-insensitive-nsstring-comparison

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