Go Program to Reverse Each Word in a String

Introduction

Reversing each word in a string involves taking each word separately, reversing its characters, and then joining the reversed words back together. This operation is often used in text processing tasks. This guide will demonstrate how to write a Go program that reverses each word in a string while keeping the word order intact.

Problem Statement

Create a Go program that:

  • Prompts the user to enter a string.
  • Reverses each word in the string.
  • Displays the string with each word reversed.

Example:

  • Input: "Hello World"
  • Output: "olleH dlroW"

Solution Steps

  1. Import the fmt and strings Packages: Use import "fmt" for formatted I/O operations and import "strings" for string manipulation functions.
  2. Write the Main Function: Define the main function, which is the entry point of every Go program.
  3. Input the String: Use fmt.Scanln or fmt.Scanf to take input from the user for the string.
  4. Split the String into Words: Use strings.Fields to split the string into individual words.
  5. Reverse Each Word: Iterate over the slice of words, reverse each word, and store it back in the slice.
  6. Join the Reversed Words: Use strings.Join to concatenate the reversed words back into a single string.
  7. Display the Resulting String: Use fmt.Println to display the string with each word reversed.

Go Program

package main

import (
    "fmt"
    "strings"
)

/**
 * Go Program to Reverse Each Word in a String
 * Author: https://www.javaguides.net/
 */
func main() {
    // Step 1: Declare a variable to hold the input string
    var input string

    // Step 2: Prompt the user to enter a string
    fmt.Print("Enter a string: ")
    fmt.Scanln(&input)

    // Step 3: Split the string into words
    words := strings.Fields(input)

    // Step 4: Reverse each word
    for i, word := range words {
        words[i] = reverseString(word)
    }

    // Step 5: Join the reversed words into a single string
    result := strings.Join(words, " ")

    // Step 6: Display the resulting string
    fmt.Println("Reversed words string:", result)
}

// Function to reverse a string
func reverseString(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

Explanation

Step 1: Declare Variables

  • The variable input is declared to store the user’s input string.

Step 2: Input the String

  • The program prompts the user to enter a string using fmt.Print. The fmt.Scanln function reads the input and stores it in the input variable.

Step 3: Split the String into Words

  • The strings.Fields function splits the input string into a slice of words based on whitespace.

Step 4: Reverse Each Word

  • The program iterates over the slice of words. For each word, it calls the reverseString function, which reverses the characters in the word.

Step 5: Join the Reversed Words

  • The strings.Join function is used to join the reversed words back into a single string, with spaces separating the words.

Step 6: Display the Resulting String

  • The program prints the resulting string with each word reversed using fmt.Println.

Reverse Function

  • The reverseString function takes a string, converts it to a slice of runes (to handle multi-byte characters correctly), and reverses the slice by swapping elements from the start and end, moving towards the center.

Output Example

Example 1:

Enter a string: Hello World
Reversed words string: olleH dlroW

Example 2:

Enter a string: GoLang is fun
Reversed words string: gnaLoG si nuf

Conclusion

This Go program demonstrates how to reverse each word in a string while keeping the word order intact. It covers basic programming concepts such as string manipulation, loops, and the use of slices and functions. This example is useful for beginners learning Go programming and understanding how to process and manipulate strings effectively.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top