Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if string is alphabetically greater than other string in objective

Tags:

I'm trying to use an if statement to work out which of 2 strings comes first alphabetically. Like with numbers and greater and less than:

if (1 < 2) { 

just with strings:

if(@"ahello" < @"bhello") { 

Or would I have to have a string containing all the letters and then check the index of the first char in each string and see which index is greater, and the index that is less than the other comes first in the alphabet and then if they are equal move on to the next char and repeat?

like image 423
Jonathan. Avatar asked May 23 '10 17:05

Jonathan.


People also ask

What does it mean to be alphabetically greater?

English translation: alphabetically higherSelected automatically based on peer agreement.

Can you compare strings alphabetically in C++?

Yes, as long as all of the characters in both strings are of the same case, and as long as both strings consist only of letters, this will work.


1 Answers

What you can do is:

NSString *stringOne = @"abcdef"; NSString *stringTwo = @"defabc";  NSComparisonResult result = [stringOne compare:stringTwo];  if (result == NSOrderedAscending) // stringOne < stringTwo     ...  if (result == NSOrderedDescending) // stringOne > stringTwo     ...  if (result == NSOrderedSame) // stringOne == stringTwo     ... 

There are also other methods for performing different kinds of comparisons (such as case-insensitivity, diacritic insensitivity, etc), but the result of the comparison can still be treated like the above. Alternatively, some people find it easier to compare result to 0. The operator used to compare result to 0 would be the same operator used in other languages where string comparisons can be done directly:

if (result < 0) // stringOne < stringTwo     ...  if (result > 0) // stringOne > stringTwo     ...  if (result == 0) // stringOne == stringTwo     ... 

Most (if not all) of the compare:... methods of NSString are wrappers for compare:options:range:locale:. The different kinds of options that you can pass can be found here.

like image 151
dreamlax Avatar answered Sep 19 '22 23:09

dreamlax