How can we reverse a simple string in Go?
Below is a very short example to reverse a string. ReverseString function created to reverse input string and returns type is String.
Example
package main
import "fmt"
type Runes []rune
func (str Runes) ReverseString() (revStr Runes) {
l := len(str); revStr = make(Runes, l)
for i := 0; i <= l/2; i++ {
revStr[i], revStr[l-1-i] = str[l-1-i], str[i]
}
return revStr
}
func (str Runes) String() string {
return string(str)
}
func main() {
inputStr := "Most Popular Golang String Functions"
strRune := Runes(inputStr)
outputStr := strRune.ReverseString()
fmt.Println("Original: ",inputStr)
fmt.Println("Reversed: ",outputStr)
}
Most Helpful This Week
Example: Stack and Caller from RUNTIME package
Regular expression to validate common Credit Card Numbers
Split a character string based on change of character
Print index and element or data from Array, Slice and Map
Example: How to use TeeReader from IO Package in Golang?
How to reads and decodes JSON values from an input stream?