Home  >  Article  >  Backend Development  >  How to Sort Strings Case-Insensitively in Go?

How to Sort Strings Case-Insensitively in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 18:41:30201browse

How to Sort Strings Case-Insensitively in Go?

Case-Insensitive Sorting Using sort.Strings() in Go

In Go, the sort.Strings() function is used to sort a list of strings. However, it doesn't provide an option for case-insensitive sorting out of the box.

Custom Comparison Function

One way to achieve case-insensitive sorting is to pass a custom comparison function to sort.Strings(). This function should return true if the first string should come before the second string in the sorted order.

The following code demonstrates how to do this:

<code class="go">package main

import (
    "fmt"
    "sort"
)

func main() {
    data := []string{"A", "b", "D", "c"}

    sort.Slice(data, func(i, j int) bool {
        return strings.ToLower(data[i]) < strings.ToLower(data[j])
    })

    fmt.Println(data) // Output: [A b c D]
}</code>

This approach creates a new string for each comparison, which can be inefficient for large lists of strings.

Rune-by-Rune Comparison

To avoid allocations, a more efficient approach is to compare the strings rune by rune, converting them to lowercase on the fly:

<code class="go">sort.Slice(data, func(i, j int) bool {
    for {
        rb, nb := utf8.DecodeRuneInString(data[j])
        if nb == 0 {
            return false
        }
        ra, na := utf8.DecodeRuneInString(data[i])
        if na == 0 {
            return true
        }
        rb = unicode.ToLower(rb)
        ra = unicode.ToLower(ra)
        if ra != rb {
            return ra < rb
        }
        data[i] = data[i][na:]
        data[j] = data[j][nb:]
    }
})</code>

Language-Specific Sorting

The collate package in Go provides more advanced functions for language-specific or culture-specific sorting orders.

The above is the detailed content of How to Sort Strings Case-Insensitively in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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