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
+12.2k Golang : "https://" not allowed in import path
+4.9k Golang : Experimental Jawi programming language
+5.7k Golang : Generate multiplication table from an integer example
+5.8k Linux/MacOSX : Search for files by filename and extension with find command
+5.2k Golang : Get S3 or CloudFront object or file information
+14.2k Golang : GUI with Qt and OpenCV to capture image from camera
+5.6k Facebook : How to force facebook to scrape latest URL link data?
+10.7k Golang : Create Temporary File
+17.1k Golang : Get future or past hours, minutes or seconds
+8.5k Golang : Take screen shot of browser with JQuery example
+16.2k Golang : Delete files by extension
+47.6k Golang : How to convert JSON string to map and slice