Go Tutorials

Go Programs

Go Sort Words in Alphabetic Order


Go Sort Words in Alphabetic Order

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, " ")
}


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,

  1. Import the fmt, sort, and strings packages.
  2. Define a function named sortWords that takes one parameter s of type string.
  3. Use the strings.Fields method to break the string into a list of words.
  4. Use the sort.Strings method to sort the list of words alphabetically.
  5. Use the strings.Join method to join the sorted list of words back into a single string.
  6. Return the sorted string.
  7. 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