How to move a word to the end of a string in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "strings"
)

func moveWordToEnd(s, word string) string {
    parts := strings.Fields(s)

    // Find and remove the first occurrence
    for i, w := range parts {
        if w == word {
            parts = append(parts[:i], parts[i+1:]...) // remove
            parts = append(parts, word)               // append at end
            break
        }
    }

    return strings.Join(parts, " ")
}

func main() {
    s := "Would you like to know more? (Explore and learn)"
    word := "like"

    result := moveWordToEnd(s, word)
    fmt.Println(result)
}



/*
run:

Would you to know more? (Explore and learn) like

*/

 



answered Feb 5 by avibootz
...