Sorting alphanumeric string array elements

While trying to order a string array by the default "sorted()" method I find the number ten comes before the number one?!

test_10
test_11
test_12
test_13
test_1
test_2
test_3
test_4
test_5
test_6
test_7
test_8
test_9

What do I have to do to maintain this order please ?

test_1
test_2
test_3
test_4
test_5
test_6
test_7
test_8
test_9
test_10
test_11
test_12
test_13

Many thanks !

Strings sort themselves lexicographically where 1 does come before 10. If you want to "group" the numbers in the string together, you can use NSString.compare(_:options:) with CompareOptions.numeric:

import Foundation

let strings = ["a10", "a1", "a23", "a2"]
let sorted = strings.sorted {
    $0.compare($1, options: .numeric) == .orderedAscending
}

print(sorted)
// ["a1", "a2", "a10", "a23"]

That said, most languages treat strings this way (or very similar). So I'd suggest that you pad the number instead to match the expected text length so as to avoid some headache later on:

// Make sure the numbers match length
test_13
test_01
test_12
test_03
2 Likes

Thank you so much, good to know about the padding as well.

Terms of Service

Privacy Policy

Cookie Policy