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
+7.4k Golang : Test if an input is an Armstrong number example
+41k Golang : Convert string to array/slice
+12.6k Golang : Handle or parse date string with Z suffix(RFC3339) example
+19.4k Golang : How to get own program name during runtime ?
+15.1k Golang : Get checkbox or extract multipart form data value example
+11.8k Golang : Print UTF-8 fonts on image example
+11.5k Golang : Convert decimal number(integer) to IPv4 address
+7.9k Golang : Oanda bot with Telegram and RSI example
+13.6k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+13.3k Golang : Check if an integer is negative or positive
+24.8k Golang : Get current file path of a file or executable
+4.8k Golang : Calculate half life decay example