String Comparison Using NSString

Dec 10, 2009   //   by Derek van Vliet   //   Development  //  3 Comments

Photo-2a

One of the most common things a programmer needs to learn how to do when faced with a new API is how to compare one string to another to see if the two are the same or how they differ.

Because of this, many APIs have created some handy string comparison features, and the NSString class in objective-c is no exception. What follows are some invaluable tools for string comparison in objective-c.

The Is-Equal Method

The NSString class responds to a message and returns whether or not the NSString you pass in is equal or not:

NSString * str = @"oranges";
BOOL res = [str isEqualToString:@"apples"];

The Compare Method

The NSString class also has a method called compare, which gives you a bit more info in the return results. It can actually tell you the difference between the two strings; whether or not the string you passed in is:

  • the same,
  • in ascending sort order to the string you call the message on or
  • in descending sort order to the string you call the message on
NSString * str = @"oranges";
NSComparisonResult res = [str compare:@"apples"];
 
switch (res) {
	case NSOrderedAscending:
		// going up
		break;
	case NSOrderedSame:
		// even steven
		break;
	case NSOrderedDescending:
		// down i go
		break;
	default:
		break;
}

Insensitivity to Case

Finally, the NSString class also features a method for comparing strings without case sensitivity. This is useful for comparing strings with unpredictable case, such as user input. Like the compare method, it returns an NSComparisonResult enumerated value which allows you to see the equality or sort-order of the two strings.

NSString * str = @"APPLES";
NSComparisonResult res = [str caseInsensitiveCompare:@"apples"];
 
switch (res) {
	case NSOrderedAscending:
		// onward and upward
		break;
	case NSOrderedSame:
		// same old
		break;
	case NSOrderedDescending:
		// downfall
		break;
	default:
		break;
}

3 Comments

Leave a comment

Our Games

Latest Tweets