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 use array in Go Programming Language?
Golang HTTP GET request with parameters
Regular expression to validate common Credit Card Numbers
How to handle HTTP Get response?
How to Decode or Unmarshal bi-dimensional array of integers?
Golang Slice vs Map Benchmark Testing
How to remove symbols from a string in Golang?
How to include and execute HTML template?
Split a string at uppercase letters using regular expression in Golang
How to set timeout for http.Get() requests in Golang?