Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case-insensitive NSString comparison

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?

like image 617
user198725878 Avatar asked Dec 20 '10 10:12

user198725878


3 Answers

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

}
like image 109
iPhoneDv Avatar answered Sep 27 '22 20:09

iPhoneDv


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?

like image 31
zoul Avatar answered Sep 27 '22 20:09

zoul


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
    //  
}
like image 30
Mike Gledhill Avatar answered Sep 27 '22 20:09

Mike Gledhill