Sort Words in Alphabetic Order in Go
In this tutorial, we will learn how to sort words in alphabetical order in Go. We will cover the basic concept of string manipulation and implement a function to perform the sorting.
What is String Manipulation
String manipulation involves altering, parsing, and analyzing strings in various ways. Sorting words in a string alphabetically is a common task in text processing.
Syntax
The syntax to sort words in alphabetical order in Go is:
import (
"fmt"
"sort"
"strings"
)
func sortWords(s string) string {
words := strings.Fields(s)
sort.Strings(words)
return strings.Join(words, " ")
}
Example 1: Sorting words in alphabetical order
We can create a function to sort words in a given string alphabetically by splitting the string into words, sorting the list of words, and then joining them back into a string.
For example,
- Import the
fmt
,sort
, andstrings
packages. - Define a function named
sortWords
that takes one parameters
of typestring
. - Use the
strings.Fields
method to break the string into a list of words. - Use the
sort.Strings
method to sort the list of words alphabetically. - Use the
strings.Join
method to join the sorted list of words back into a single string. - Return the sorted string.
- In the main function, call the
sortWords
function with a sample string and print the result.
Go Program
package main
import (
"fmt"
"sort"
"strings"
)
func sortWords(s string) string {
words := strings.Fields(s)
sort.Strings(words)
return strings.Join(words, " ")
}
func main() {
// Sample string
sampleString := "hello world welcome to go programming"
// Sort words in the sample string
result := sortWords(sampleString)
// Print the result
fmt.Println("Sorted words:", result)
}
Output
Sorted words: go hello programming to welcome world