k3a
k3a

Reputation: 1391

Comparing strings of different lengths with compare:options:range: produces wrong result

Why does this comparison result in NO?

BOOL areTheSame = NSOrderedSame == [@"th" compare:@"They" options:NSCaseInsensitiveSearch range:NSMakeRange(0, 2)];

When I test it on @"th" and @"Th" it's YES.

What am I missing here?

Upvotes: 3

Views: 1052

Answers (1)

jscs
jscs

Reputation: 64022

This is counter-intuitive, but the range argument only applies to the receiver. The length of the other string (the argument to compare:) isn't range-limited. Your call reduces @"th" to the range {0,2}, which produces @"th" (i.e., this has no effect), and then compares it to @"They".

You will see that this:

NSComparisonResult comp = [@"They" compare:@"th" 
                                   options:NSCaseInsensitiveSearch 
                                     range:NSMakeRange(0, 2)];
BOOL areTheSame = comp == NSOrderedSame;

produces the result you expect, because it cuts the receiver (@"They") down (to @"Th") and then does the comparison.

Upvotes: 6

Related Questions