Skip to content
Kavachकवच

Sorting: Text

● Beginner3 min

Text sorts by Unicode code point, character by character: the same on every machine, whatever its language settings.

fn main() {
    print(["banana", "Apple", "cherry", "apple"].sort())
    print(["zebra", "Éclair", "eclair"].sort())
    print(["file10", "file9", "file1"].sort())
    print(['b', 'A', 'a', '1'].sort())
}

The program ran and printed:

kavach run text.kav

["Apple", "apple", "banana", "cherry"]["eclair", "zebra", "Éclair"]["file1", "file10", "file9"]['1', 'A', 'a', 'b']
text.kav: Kavach code, then what running it prints
  • Uppercase letters come before lowercase ones: "Apple" before "apple".
  • Letters with accents come after z: É is code point 201, z is 122.
  • Digits are characters too: "file10" comes before "file9", because 1 comes before 9.

To ignore case, sort by the lowercase text. Words equal apart from case keep their order:

fn main() {
    const words = ["banana", "Apple", "cherry", "apple"]
    print(words.sort_by(w => w.lower()))
}

The program ran and printed:

kavach run ignore-case.kav

["Apple", "apple", "banana", "cherry"]
ignore-case.kav: Kavach code, then what running it prints