The Go Cookbook

Maintained by SuperOrbital.

A community built and contributed collection of practical recipes for real world Golang development.

View project on GitHub

Reversing a String by Word or Character

How do I reverse a string by word or character?

Reversing a string by character is very similar to the process to reverse an array. The difference is that strings are immutable in Go. Therefore, we must first convert the string to a mutable array of runes ([]rune), perform the reverse operation on that, and then re-cast to a string.

package main

import "fmt"

func reverse(s string) string {
	chars := []rune(s)
	for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {
		chars[i], chars[j] = chars[j], chars[i]
	return string(chars)

func main() {
	fmt.Printf("%v\n", reverse("abcdefg"))
$ go run test_reverse_by_character.go

Reversing a string by word is a similar process. First, we convert the string into an array of strings where each entry is a word. Next we apply the normal reverse loop to that array. Finally, we smush the results back together into a string that we can return to the caller.

package main

import (

func reverse_words(s string) string {
	words := strings.Fields(s)
	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, " ")

func main() {
	fmt.Println(reverse_words("one two three"))
$ go run test_reverse_by_word.go
three two one