sort an string array by content length in go

To sort a string array by content length in Go, we need to implement a custom string comparison function that compares the lengths of the strings in the array. Here's an example implementation:

main.go
package main

import (
    "fmt"
    "sort"
)

func main() {
    arr := []string{"apple", "banana", "cherry", "date", "elderberry", "fig"}

    // Define the custom comparison function
    cmpFunc := func(i, j int) bool {
        return len(arr[i]) < len(arr[j])
    }

    // Use the custom comparison function to sort the array
    sort.Slice(arr, cmpFunc)

    // Print the sorted array
    fmt.Println(arr)
}
413 chars
22 lines

In this example, we define a string array arr containing six fruit names. We then define a custom comparison function cmpFunc that sorts the strings in arr based on their lengths. We pass cmpFunc to the sort.Slice function which modifies the array in place. Finally, we print the sorted array to the console. The output should be:

main.go
[date fig apple banana cherry elderberry]
42 chars
2 lines

related categories

gistlibby LogSnag