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 find the type of the variable by different ways in Golang?
Golang Get current Date and Time in EST, UTC and MST?
Example: How to use ReadFull from IO Package in Golang?
Subtract N number of Year, Month, Day, Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to current date-time.
How to add Watermark or Merge two image?
How to use function from another file golang?