reverse a string in golang
Here is a solution to reverse a string in Go, along with explanations for each step:
package main
import (
"fmt"
)
func main() {
str := "Hello, World!" // The string to be reversed
reversedStr := reverseString(str) // Calling the reverseString function
fmt.Println(reversedStr) // Printing the reversed string
}
// Function to reverse a string
func reverseString(s string) string {
// Converting the string into a slice of runes
runes := []rune(s)
// Initializing two pointers, one at the start and the other at the end of the slice
i, j := 0, len(runes)-1
// Swapping the characters using the two pointers until they meet in the middle
for i < j {
runes[i], runes[j] = runes[j], runes[i]
i++
j--
}
// Converting the slice of runes back into a string and returning it
return string(runes)
}
Explanation:
1. The reverseString
function takes a string s
as input and returns the reversed string.
2. Inside the function, the string s
is converted into a slice of runes using []rune(s)
. This is necessary because Go strings are immutable, but slices are mutable.
3. Two pointers, i
and j
, are initialized at the start and end of the slice respectively.
4. A for
loop is used to swap the characters at i
and j
until they meet in the middle. This is done by using the syntax runes[i], runes[j] = runes[j], runes[i]
.
5. Finally, the reversed slice of runes is converted back into a string using string(runes)
and returned from the function.
6. In the main
function, a string str
is assigned the value "Hello, World!"
.
7. The reverseString
function is called with str
as the argument, and the returned value is assigned to reversedStr
.
8. The reversed string is printed to the console using fmt.Println(reversedStr)
.
I hope this explanation helps!