How to reverse the order of the words in a string with Go

1 Answer

0 votes
package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "aaa bbb ccc ddd eee";
    
    reversedStringWords := reverseWords(str)
    
    fmt.Println(reversedStringWords)
}

func reverseWords(str string) string {
    words := strings.Fields(str)
    reversed := make([]string, len(words))

    for i := range words {
        reversed[len(words)-1-i] = words[i]
    }

    return strings.Join(reversed, " ")
}




/*
run:

eee ddd ccc bbb aaa

*/

 



answered Feb 6, 2025 by avibootz
edited Feb 6, 2025 by avibootz
...