Wednesday, 9 May 2012

String Comparison in Objective C




 In Objective C, strings can be compared using 'isEqualToString'.
 
NSString *myString1 = @”Suraj”;
NSString *myString2 = @”Suraj”;
NSString *myString3 = @”Mirajkar”;

if ([myString1 isEqualToString: myString2])
 {
          NSLog(@”String1: %@ is Equal to String2: %@”, myString1, myString2); 
 }
 else
 {
            NSLog(@”String1: %@ is Not Equal to String2: %@”, myString1, myString2);
 }

 if ([myString1 isEqualToString: myString3])
 {
            NSLog(@”String1: %@ is Equal to String3: %@”, myString1, myString3);
 }
 else
 {
           NSLog(@”String1: %@ is Not Equal to String3: %@”, myString1, myString3);
 }

                   // Output :
                   // String1: Suraj is Equal to String2: Suraj
                   // String1: Suraj is Not Equal to String3: Mirajkar

 For Case Insensitive String Comparison:
 
NSString *myString1 = @”Suraj”;
NSString *myString2 = @”suraj”;

if ([myString1 caseInsensitiveCompare: myString2] == NSOrderedSame)   
 {
          NSLog(@”String1: %@ is Equal to String2: %@”, myString1, myString2); 
 }
 else
 {
            NSLog(@”String1: %@ is Not Equal to String2: %@”, myString1, myString2);
 }

                    // Output :
                   // String1: Suraj is Equal to String2: suraj