Search code examples
ballerina

How to sort a string in Ballerina


i.e. from "cba" to "abc". Given that it seems the lang.string module lacks sorting support and the array:sort() function doesn't accept strings? Currently, my workaround involves converting the string to a string:Char[] and then using arrays:sort().


Solution

  • It is possible to convert the string to string:Char[] and do it.

    string str = "cdba";
    string:Char[] arr = [];
    foreach string:Char ch in str {
        arr.push(ch);
    }
    string sorted = string:'join("",...arr.sort());
    

    Alternatively, you could probably use a query expression.

    string str = "cdba";
    string sorted = from string char in str order by char select char;