ADVERTISEMENT
ADVERTISEMENT

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)

Parameter(s):

  • 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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.