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:
- Define the main package: Create a package named
main
. - Main Function: The
main
function is the entry point of the program. - Input String: Define a string that you want to reverse.
- Reverse the String: Use a loop to reverse the string by iterating from the end to the beginning.
- 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 thereverseString
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:
- Save the code in a file named
main.go
. - Compile and run the program using the command:
go run main.go
.
Explanation of the Go Program:
- Package Definition: The program is part of the
main
package, which defines the entry point of the application. - Main Function:
- Initializes a string
original
with a value to be reversed. - Calls the
reverseString
function and stores the result inreversed
. - Prints both the original and reversed strings to the console.
- Initializes a string
- 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.