C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: Runes can represent more than one byte. Runes support 2-byte characters. Logically a rune is a character.
For: We use a for-loop, with a decrementing iteration, to access our slice of runes. We build up a slice of the runes in reverse order.
ForReturn: Our func returns a string based on the reversed contents of the rune slice. We just use runes internally to process the string.
Golang program that reverses a string, uses runes
package main
import "fmt"
func reverse(value string) string {
// Convert string to rune slice.
// ... This method works on the level of runes, not bytes.
data := []rune(value)
result := []rune{}
// Add runes in reverse order.
for i := len(data) - 1; i >= 0; i-- {
result = append(result, data[i])
}
// Return new string.
return string(result)
}
func main() {
// Test our method.
value1 := "cat"
reversed1 := reverse(value1)
fmt.Println(value1)
fmt.Println(reversed1)
value2 := "abcde"
reversed2 := reverse(value2)
fmt.Println(value2)
fmt.Println(reversed2)
}
Output
cat
tac
abcde
edcba
But: For a string with 2-byte chars, runes will preserve the data. Accessing bytes will meanwhile cause some corruption.
Opinion: For a simple method like string reversal, keeping the data correct is probably more important than max performance.