Golang : Reverse by word
This tutorial will show you how to reverse the order of words in a string. Reversing the words or elements order can be useful in queuing job or performing certain task that need LIFO(Last In First Out) order. In this simple example, the words order are reversed
package main
import (
"fmt"
"strings"
)
func reverse(s string) string {
words := strings.Fields(s) // tokenize each words from input string
totalLength := len(words)
// reverse the order(no sorting!)
for i, j := 0, totalLength-1; i < j; i, j = i+1, j-1 {
words[i], words[j] = words[j], words[i]
}
// return the reversed words
return strings.Join(words, " ")
}
func main() {
reversed := reverse("apple durian kiwi banana")
fmt.Println(reversed)
}
Output :
banana kiwi durian apple
NOTE :
Now, this is different from Sort.Reverse()
function, we are looking to reverse the order of the words, not sorting the order. If you are looking for sort and reverse, see here https://www.socketloop.com/tutorials/golang-sort-and-reverse-sort-a-slice-of-strings
Reference :
See also : Golang : Sort and reverse sort a slice of strings
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.9k Golang : How to determine a prime number?
+14.9k Golang : convert string or integer to big.Int type
+10.8k Golang : Convert a rune to unicode style string \u
+5.6k Golang : Humanize and Titleize functions
+4.6k Unix/Linux : How to find out the hard disk size?
+21.4k Golang : simulate tail -f or read last line from log file example
+6.4k Golang : How to convert strange string to JSON with json.MarshalIndent
+9.5k Golang : Roll the dice example
+6.3k Golang : Check to see if *File is a file or directory
+4.4k Golang : Return multiple values from function
+17.8k Golang : How to make function callback or pass value from function as parameter?
+7.9k Golang : What is the default port number for connecting to MySQL/MariaDB database ?