Go Program to Reverse a String

1. Introduction

Strings are a fundamental aspect of many programming tasks. In Go, strings are immutable sequences of bytes, and reversing them requires a bit of care due to UTF-8 encoding. This blog post will guide you through the steps to reverse a string in Go.

2. Program Overview

Our Go program is poised to:

1. Solicit a string input from the user.

2. Employ a character-by-character traversal to reverse the string.

3. Showcase the reversed string.

3. Code Program

// Our endeavor begins with the announcement of the main package.
package main

// We draft the fmt package to harness its input and output capabilities.
import "fmt"

// Function to manually 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)
}

// The epicenter of our program, the main function.
func main() {
    var originalString string

    // Encouraging the user to input a string.
    fmt.Print("Enter a string: ")
    fmt.Scanln(&originalString)

    // Unveiling the reversed string to the user.
    fmt.Printf("Reversed string of \"%s\" is: \"%s\"\n", originalString, reverseString(originalString))
}

Output:

Let's say the user decides to input the string programming. The program's disclosure will be:
Reversed string of "programming" is: "gnimmargorp"

4. Step By Step Explanation

1. Package and Import: Our expedition starts with the package main declaration, indicating the entry point of the program. To manage I/O operations, the fmt package is employed.

2. Reversing String Function: The reverseString function initiates the reversal process by first converting the string into a slice of runes. This allows us to manipulate individual characters. A two-pointer approach then ensues, swapping characters starting from the string's extremities and moving inwards.

3. User Engagement & Output: The originalString variable is the container for the user's input. Once the input string is fetched, the program invokes the reverseString function and displays the reversed string.

Comments