How to reverse the characters in a string in Golang?

To reverse the characters in a string in Golang, you can use the following steps:

  1. Convert the string into a slice of runes.
  2. Iterate through the slice and swap the characters at opposite positions.
  3. Convert the slice of runes back into a string.

Here's an example implementation:

package main import ( "fmt" ) func reverseString(s string) string { // Convert string to a slice of runes runes := []rune(s) // Iterate through the slice and swap characters at opposite positions for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } // Convert slice of runes back to string return string(runes) } func main() { s := "Hello, World!" reversed := reverseString(s) fmt.Println(reversed) // Outputs: "!dlroW ,olleH" }

In this example, we define a reverseString function that takes a string as input and returns the reversed string. We convert the string to a slice of runes, iterate through the slice to swap the characters, and then convert the slice back to a string. Finally, we call the reverseString function in the main function to demonstrate the reversal.