Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Strings in Cocoa

I have tried:

- (NSString*) generateString
{
    NSString* stringToReturn = @"thisString";
    return stringToReturn;
}

- (void) otherMethod
{
    NSString *returnedString = [self generateString];
    if (returnedString == @"thisString")
    { // Do this }
    else if (returnedString == @"thatString")
    { // Do that }
}

Which never matches.

I have then tried

if ([returnedString compare:@"thisString"] == 1)

But the compare method always returns 1 for me, even when comparing with a different string.

What is the correct way to do this, and what result should I expect?

like image 957
mattdwen Avatar asked May 19 '09 07:05

mattdwen


People also ask

What is the best way to compare strings?

The right way of comparing String in Java is to either use equals(), equalsIgnoreCase(), or compareTo() method. You should use equals() method to check if two String contains exactly same characters in same order. It returns true if two String are equal or false if unequal.

What is string comparison method?

Java String compareTo() MethodThe method returns 0 if the string is equal to the other string. A value less than 0 is returned if the string is less than the other string (less characters) and a value greater than 0 if the string is greater than the other string (more characters).

How do you compare string sizes?

strcmp is used to compare two different C strings. When the strings passed to strcmp contains exactly same characters in every index and have exactly same length, it returns 0. For example, i will be 0 in the following code: char str1[] = "Look Here"; char str2[] = "Look Here"; int i = strcmp(str1, str2);


1 Answers

First of all, you are using the == operator to compare two object pointers (of type NSString *). So that returns true when the pointers are the same, not when the strings have the same contents. If you wanted to compare whether two strings are the same, you should use isEqualToString: or isEqual: (isEqual: is more general as it works for all types of objects).

Second, compare: returns 0 (NSOrderSame) when they are the same, and 1 (NSOrderedDescending) when the first is greater than the second. So in fact it returns 1 only when they are different (specifically, when the first is greater than the second).

like image 64
newacct Avatar answered Sep 23 '22 00:09

newacct