Home »
Golang »
Golang Reference
Golang sort.Strings() Function with Examples
Golang | sort.Strings() Function: Here, we are going to learn about the Strings() function of the sort package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 14, 2021
sort.Strings()
The Strings() function is an inbuilt function of the sort package which is used to sort a given slice of Strings (string type of elements) in increasing order (ascending order).
It accepts a parameter (x []string) and returns nothing.
Syntax
func Strings(x []string)
Parameters
- x : Slice of Strings to be sorted in ascending order.
Return Value
None.
Example 1
// Golang program to demonstrate the
// example of sort.Strings() Function
package main
import (
"fmt"
"sort"
)
func main() {
x := []string{"Banana", "Apple", "Cat", "Mango"}
fmt.Println("x (Before):", x)
sort.Strings(x)
fmt.Println("x (After):", x)
fmt.Println()
x = []string{"Tigor", "Venue", "City", "Creta"}
fmt.Println("x (Before):", x)
sort.Strings(x)
fmt.Println("x (After):", x)
}
Output:
x (Before): [Banana Apple Cat Mango]
x (After): [Apple Banana Cat Mango]
x (Before): [Tigor Venue City Creta]
x (After): [City Creta Tigor Venue]
Example 2
// Golang program to demonstrate the
// example of sort.Strings() Function
package main
import (
"fmt"
"sort"
)
func main() {
x := []string{"Banana", "Apple", "Cat", "Mango"}
// Printing x, type, sorting status
fmt.Println("x:", x)
fmt.Printf("%T, %v\n", x, sort.StringsAreSorted(x))
// Sorting x
sort.Strings(x)
// Printing x, type, sorting status
fmt.Println("x:", x)
fmt.Printf("%T, %v\n", x, sort.StringsAreSorted(x))
fmt.Println()
x = []string{"Tigor", "Venue", "City", "Creta"}
// Printing x, type, sorting status
fmt.Println("x:", x)
fmt.Printf("%T, %v\n", x, sort.StringsAreSorted(x))
// Sorting x
sort.Strings(x)
// Printing x, type, sorting status
fmt.Println("x:", x)
fmt.Printf("%T, %v\n", x, sort.StringsAreSorted(x))
}
Output:
x: [Banana Apple Cat Mango]
[]string, false
x: [Apple Banana Cat Mango]
[]string, true
x: [Tigor Venue City Creta]
[]string, false
x: [City Creta Tigor Venue]
[]string, true
Golang sort Package »