flux
flux

Reputation: 395

Sorting array by integer value contained in string

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)?

Upvotes: 2

Views: 747

Answers (2)

Bruno Koga
Bruno Koga

Reputation: 3874

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];
}];

Upvotes: 0

Valent Richie
Valent Richie

Reputation: 5226

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];
}];

Upvotes: 1

Related Questions