Introduction
Reversing a string is a common operation in programming where the characters of the string are rearranged in reverse order. This guide will demonstrate how to write a Go program that takes a string as input and outputs the string reversed.
Problem Statement
Create a Go program that:
- Prompts the user to enter a string.
- Reverses the string.
- Displays the reversed string.
Example:
- Input:
Hello - Output:
olleH
Solution Steps
- Import the fmt Package: Use
import "fmt"to include the fmt package for formatted I/O operations. - Write the Main Function: Define the
mainfunction, which is the entry point of every Go program. - Input the String: Use
fmt.Scanlnto take input from the user for the string. - Reverse the String: Convert the string to a slice of runes and reverse the slice.
- Display the Reversed String: Use
fmt.Printlnto display the reversed string.
Go Program
package main
import "fmt"
/**
* Go Program to Reverse 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: Reverse the string by converting it to a slice of runes
reversed := reverseString(input)
// Step 4: Display the reversed string
fmt.Println("Reversed string:", reversed)
}
// 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
inputis 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. Thefmt.Scanlnfunction reads the input and stores it in theinputvariable.
Step 3: Reverse the String
- The string is converted to a slice of runes to properly handle any Unicode characters. The function
reverseStringis used to reverse the slice by swapping elements from the start and end until the middle of the slice is reached.
Step 4: Display the Reversed String
- The reversed slice of runes is converted back to a string and displayed using
fmt.Println.
Reverse Function
- The
reverseStringfunction takes a string, converts it into a slice of runes, and swaps the elements to reverse the order of the string. The final reversed string is returned to the caller.
Output Example
Example 1:
Enter a string: Hello
Reversed string: olleH
Example 2:
Enter a string: GoLang
Reversed string: gnaLoG
Conclusion
This Go program demonstrates how to reverse a string by converting it to a slice of runes, reversing the slice, and converting it back to a string. It covers basic programming concepts such as string manipulation, slices, and loops. This example is useful for beginners learning Go programming and understanding how to work with strings and slices in Go.