2

I have a concatenated string with two pieces of information. The last three characters in the string is a number. I have about 10 of these in an array and I want to sort the array by having the strings with the largest number at the lowest index.

How can a sort an array like this (by the last three characters integer value)?

flux
  • 395
  • 1
  • 2
  • 13
  • Use one of the `sortedArrayUsing...` methods. You have to write the method/function/comparator that looks at the strings, finds the trailing number, and converts to int before comparing. – Hot Licks Jun 03 '13 at 00:27
  • Note that sorting the largest number to the front is merely a matter of having your method/function/comparator be "backwards" -- compare second to first vs first to second, eg. – Hot Licks Jun 03 '13 at 02:43

2 Answers2

1

There is no built-in function to sort array by last three characters of string objects, since it is just too specific. But we can always break down the issue at hand.

First is how to sort an array. There are many ways to do it, for example as explained here: How to sort an NSMutableArray with custom objects in it?

Let's say we will proceed with the last shiny option which is using block.

Now, the second issue for your particular case is that you will need to get the last three characters from the string. An example of how to do it can be obtained from here: how to capture last 4 characters from NSString

Putting it all together:

NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    NSString *first = [(NSString*)a substringFromIndex:[a length]-3];
    NSString *second = [(NSString*)b substringFromIndex:[b length]-3];
    return [second compare:first];
}];
Community
  • 1
  • 1
Valent Richie
  • 5,226
  • 1
  • 20
  • 21
  • This won't sort the values in reverse order as mentioned in the question. Change it to `return [second compare:first];` – rmaddy Jun 03 '13 at 03:08
0

You can try something like: (This code was not tested)

NSArray *unorderedArray; //This is your array
NSArray *orderedArray = [unorderedArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
    NSString *string1 = [(NSString *)obj1;
    NSString *string2 = (NSString *)obj2;
    string1 = [string1 substringFromIndex:[string1 length] - 3]; //3 last chars
    string2 = [string2 substringFromIndex:[string2 length] - 3]; //3 last chars

    return [string2 compare:string1];
}];
Bruno Koga
  • 3,864
  • 2
  • 34
  • 45