Drill

ProblemsGo › warmup

Reverse the order of the words

easywarmupStringsParsingGo

A text filter turns a sentence back to front, word by word, without disturbing the words themselves.

reverseWords(text: string) → string

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func reverseWords(text string) string {
	
}

Worked examples

CallResult
reverseWords("the quick brown fox")"fox brown quick the"
reverseWords(" a b ")"b a"
reverseWords("one")"one"
reverseWords("")""

Hint

Split on whitespace, reverse the list, join with a single space.

Reference solution in Go
func reverseWords(text string) string {
	words := strings.Fields(text)
	for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 {
		words[i], words[j] = words[j], words[i]
	}
	return strings.Join(words, " ")
}

The same problem in another language

More warmup problems in Go