Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #297 Sort a list of strings, case-insensitively

Sort the string list data in a case-insensitive manner.

The sorting must not destroy the original casing of the strings.

import java.util.ArrayList;
import java.util.Comparator;
data.sort(new Comparator<String>()
{
	@Override
	public int compare(String o1, String o2)
	{
		return o1.compareToIgnoreCase(o2);
	}
	
});
data.sort((a, b) => a.toUpperCase().compareTo(b.toUpperCase()));
import (
	"sort"
	"unicode"
	"unicode/utf8"
)
func lessCaseInsensitive(s, t string) bool {
	for {
		if len(t) == 0 {
			return false
		}
		if len(s) == 0 {
			return true
		}
		c, sizec := utf8.DecodeRuneInString(s)
		d, sized := utf8.DecodeRuneInString(t)

		lowerc := unicode.ToLower(c)
		lowerd := unicode.ToLower(d)

		if lowerc < lowerd {
			return true
		}
		if lowerc > lowerd {
			return false
		}

		s = s[sizec:]
		t = t[sized:]
	}
}

sort.Slice(data, func(i, j int) bool { return lessCaseInsensitive(data[i], data[j]) })
import (
	"sort"
	"strings"
)
sort.Slice(data, func(i, j int) bool {
	return strings.ToLower(data[i]) < strings.ToLower(data[j])
})
import "cmp"
import "slices"
slices.SortFunc(data, func(a, b string) int {
	return cmp.Compare(strings.ToLower(a), strings.ToLower(b))
})
Classes;
data.sort;
@data = sort { lc($a) cmp lc($b) } @data;
data.sort(key=str.lower)
data.sort_by!(&:downcase)

New implementation...