I want to sort the Turkish name of countries in Dart, however I couldn’t find a method to customize the alphabetical order during sorting operation like collations in Java.
For example when I sort with a standard string compareTo
method I get:
var countries = ["Belgrad", "Belçika", "Irak", "İran", "Sudan", "Şili", "Çek Cumhuriyeti", "Cezayir", "Ukrayna", "Ürdün"];
countries.sort((firstString, secondString) => firstString.compareTo(secondString));
print(countries);
It prints in a wrong order based on English alphabetical order:
[Belgrad, Belçika, Cezayir, Irak, Sudan, Ukrayna, Çek Cumhuriyeti, Ürdün, İran, Şili]
Because in Turkish alphabet the order of letters is "a", "b", "c", "ç", "d", "e", "f", "g", "ğ", "h", "ı", "i", "j", "k", "l", "m", "n", "o", "ö", "p", "r", "s", "ş", "t", "u", "ü", "v", "y", "z", the correct order should be like:
(note that Belçika must come before Belgrad because ç < g in Turkish)
[Belçika, Belgrad, Cezayir, Çek Cumhuriyeti, Irak, İran, Sudan, Şili, Ukrayna, Ürdün]
2
Answers
Although, Lucie's answer works, I ended up writing my own extension for strings for Turkish alphabet operations for the general use. The Turkish alphabet has a weird issue with capital letter "I". Its lowercase form is "ı" (not "i"). Also, the lowercase letter "i" has an uppercase form as "İ". Dart does not support this minor detail for the Turkish in its
toLowerCase
function.Sorting strings with Turkish characters can be done with the snippet below. (based on Daniel's answer):
The example list below is sorted with a standard
sort()
method of list using our extension method:You can define what sorting method you want. If I take your example, you can do something like:
What I did here:
Notes:
I did not check if the country in countries List is not empty,
a[0]
orb[0]
would throw an exception in this case, don’t forget it.I also had to add "i̇" in the turkishOrder List, in order to have İran at the right place.
Edit: the solution above only compares the first letter. Here is an updated version of the comparison function, to compare all letters: