In Swift, you can sort characters in a string by converting the string to an array of characters, sorting the array, and then converting it back to a string.
In this example,
str
.Array(str)
constructor.sort()
method.joined()
method.let str = "hello world"
let sortedStr = String(Array(str).sorted())
print("Sorted string in ascending order: \(sortedStr)")
Sorted string in ascending order: dehllloorw
In this example,
str
.Array(str)
constructor.sort()
method with a custom comparator.joined()
method.let str = "hello world"
let sortedStr = String(Array(str).sorted(by: >))
print("Sorted string in descending order: \(sortedStr)")
Sorted string in descending order: wroolllhed
In this tutorial, we learned How to Sort Characters in String in Swift language with well detailed examples.