Search code examples
stringsortingcollectionsvala

How to sort strings in Vala?


Two things jump to mind: using a Gee.TreeSet, which is always sorted, or calling Gee.ArrayList.sort.

The first feels like overkill and I can't find documentation on the other. What's the smartest way to proceed?


Solution

  • If you have an array, you can try using the POSIX qsort function like this:

    int cmpfunc(ref string x, ref string y) {
        return Posix.strcmp(x, y);
    }
    var strs = new string[] {"x", "z", "fred"};
    Posix.qsort (strs, strs.length, sizeof(string), (Posix.compar_fn_t) cmpfunc);
    

    and be sure to compile with --pkg posix. You may want to use strcoll instead if sorting for the user.