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
How to Unmarshal nested JSON structure?
Encoding and Decoding using json.Marshal and json.Unmarshal
How to get first and last element of slice in Golang?
Dynamic XML parser without Struct in Go
How to use for and foreach loop?
How to rotate an image?
Sierpinski triangle in Go Programming Language
How to declare and access pointer variable?
How to collect information about garbage collection?
Copy an array by value and reference into another array