Switching to a new programming language can cost a lot of work for programmers. One of the most common task that a programmer do during his work is string comparison.

Each programming language provides its own implementation to compare strings, some programming languages like C/C++ provides very poor API's while others provides very complex and rich API's.

Objective-C provides a very powerful set of API's to handle strings. 

 

 

The NSString class has three powerful methods to compare strings,

  • isEqualToString
  • compare
  • caseInsensitiveCompare

The isEqualToString method returns YES if the two strings are equal and NO if they are not.  isEqualToString is a case sensitive method.

 

    NSString *myString=@"Ciao";

    BOOL res = [myString isEqualToString:@"cc"];

The compare method is a case sensitive method, it returns a bit more info than isEqualToString. It tells the differences between the two NSString's. It can discriminate if the two strings are equal of if the first one comes before the second one, and vice-versa.

 

    NSString * str = @"Ciao";

    NSComparisonResult res = [str compare:@"cc"];

    

    switch (res) {

        case NSOrderedAscending:

            // the first NSString comes before the second one

            break;

        case NSOrderedSame:

            // They are equal

            break;

        case NSOrderedDescending:

            //  the first NSString comes after the second one

            break;

        default:

            break;

    }

If you want to make a case  insensitive comparison, simply you have to change the method you are using:

 

    NSString * str = @"Ciao";

    NSComparisonResult res = [str caseInsensitiveCompare:@"cc"];

    

    switch (res) {

        case NSOrderedAscending:

            // the first NSString comes before the second one

            break;

        case NSOrderedSame:

            // They are equal

            break;

        case NSOrderedDescending:

            //  the first NSString comes after the second one

            break;

        default:

            break;

    }

Gg1.