Home > Backend Development > Golang > How to Achieve Case-Insensitive Sorting in Go with sort.Strings()?

How to Achieve Case-Insensitive Sorting in Go with sort.Strings()?

Mary-Kate Olsen
Release: 2024-11-02 10:34:02
Original
208 people have browsed it

How to Achieve Case-Insensitive Sorting in Go with sort.Strings()?

Case Insensitive Sorting in Golang with sort.Strings()

In Python, case-insensitive sorting is often achieved using the key parameter of the sorted() function, which allows for custom comparison functions. However, in Go's sort.Strings(), there is no direct equivalent.

To perform case-insensitive sorting in Go, we can leverage Go's powerful slicing capabilities. One approach is to create a custom comparison function that compares the strings' lowercase versions:

<code class="go">sort.Strings(data, func(i, j int) bool {
    return strings.ToLower(data[i]) < strings.ToLower(data[j])
})</code>
Copy after login

This method works well for small data sets, but it can result in excessive string allocations for large inputs.

For more efficient sorting, we can compare the strings rune by rune while ignoring their case:

<code class="go">func lessLower(sa, sb string) bool {
    for {
        rb, nb := utf8.DecodeRuneInString(sb)
        if nb == 0 {
            return false
        }

        ra, na := utf8.DecodeRuneInString(sa)
        if na == 0 {
            return true
        }

        rb = unicode.ToLower(rb)
        ra = unicode.ToLower(ra)

        if ra != rb {
            return ra < rb
        }

        sa = sa[na:]
        sb = sb[nb:]
    }
}

sort.Strings(data, func(i, j int) bool {
    return lessLower(data[i], data[j])
})</code>
Copy after login

This approach avoids unnecessary allocations by directly comparing the runes of the strings.

For further flexibility and language-specific sorting, consider using the collate package, which provides locales and language-specific collation rules.

The above is the detailed content of How to Achieve Case-Insensitive Sorting in Go with sort.Strings()?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template