Reversing a Unicode String in Go
Here's a Go function that correctly reverses strings containing Unicode characters (including multi-byte runes):
package main
import (
"fmt"
"unicode/utf8"
)
// ReverseString reverses a Unicode string correctly
func ReverseString(s string) string {
// Convert string to rune slice to handle Unicode characters properly
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 back to string
return string(runes)
}
func main() {
// Test cases
fmt.Println(ReverseString("Hello, 世界")) // Output: 界世 ,olleH
fmt.Println(ReverseString("Go😀")) // Output: 😀oG
fmt.Println(ReverseString("café")) // Output: éfac
}
Key Points:
- Unicode Handling: Uses
[]rune instead of []byte to properly handle multi-byte Unicode characters
- Efficiency: Performs the reversal in O(n) time with O(n) space complexity
- Correctness: Works with:
- ASCII characters
- Multi-byte Unicode characters (like Chinese)
- Emoji and other special symbols
- Combining characters
Alternative Implementation:
For very large strings where memory is a concern, you could process the string as runes without converting to a slice first:
func ReverseString(s string) string {
size := len(s)
buf := make([]byte, size)
for i, r := range s {
size -= utf8.RuneLen(r)
utf8.EncodeRune(buf[size:], r)
}
return string(buf)
}