Go Program to Reverse a Given String

 

 

Go Program to Reverse a Given String

This page contains a Go program that reverses a given string. The program uses basic string manipulation techniques to achieve this task.

Program Explanation

The Go program to reverse a string follows these steps:

  1. Define the main package: Create a package named main.
  2. Main Function: The main function is the entry point of the program.
  3. Input String: Define a string that you want to reverse.
  4. Reverse the String: Use a loop to reverse the string by iterating from the end to the beginning.
  5. Print the Result: Output the reversed string to the console.

Go Program Code

// Package main defines the entry point of the program.
package main

import (
    "fmt"
)

// main function is the entry point of the program.
func main() {
    // Define the string to be reversed
    original := "Hello, World!"
    
    // Call the reverseString function and store the result
    reversed := reverseString(original)
    
    // Print the original and reversed strings
    fmt.Println("Original String:", original)
    fmt.Println("Reversed String:", reversed)
}

// reverseString function takes a string as input and returns the reversed string.
func reverseString(s string) string {
    // Convert the string to a rune slice to handle multi-byte characters
    runes := []rune(s)
    
    // Reverse the rune slice
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    
    // Convert the rune slice back to a string and return it
    return string(runes)
}

Program Details

The Go program consists of the following components:

  • main Function: The entry point of the program where the string is defined and the reverseString function is called.
  • reverseString Function: A function that takes a string as input, reverses it using rune slices, and returns the reversed string.

Running the Program

To run the program:

  1. Save the code in a file named main.go.
  2. Compile and run the program using the command: go run main.go.

 

Explanation of the Go Program:

  1. Package Definition: The program is part of the main package, which defines the entry point of the application.
  2. Main Function:
    • Initializes a string original with a value to be reversed.
    • Calls the reverseString function and stores the result in reversed.
    • Prints both the original and reversed strings to the console.
  3. reverseString Function:
    • Converts the input string to a slice of runes to handle multi-byte characters correctly.
    • Uses a loop to reverse the rune slice by swapping elements from the beginning and end.
    • Converts the rune slice back to a string and returns it.

Leave a Reply

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