How to Replace Characters in a String in Golang

We can replace characters in a String using the Golang library functions. This post will focus on library functions and what other options available for string replacement in Go.

Can we use direct assignment to replace String Contents?

When we have a string and we directly want to assign values at different index, the function does not work. The reason being Go doesn’t support string mutability out of the box.

s := "hello"
	
s[0] = "a"        // Error: cannot assign to s[0]

Strings Replace() method

Since the direct assignment is unavailable we need the library functions to replace the string. The strings package contains the Replace() method. The replace method replaces the string characters and returns a new resultant string. First, we need to import the strings package.

import "strings"

Now, we can use the replace function to replace directly in the string. Here is an example.

import (
	"fmt"
	"strings"
)

func main() {
	
	s := "hello world"
	fmt.Println(s)             // hello world
	
	ns := strings.Replace(s, "hello", "bye", -1)
	fmt.Println(ns)            // bye world
}

The replace function takes four arguments the original string, the value to be replaced, the replacing value and the number of occurrences. Here in the number of occurrences, we provide -1 which indicates the function that it should replace all occurrences of it.

Be aware, that the values provided in the function are case-sensitive.

Here is an example showing how the number of occurrences can be used to replace strings using the replace method.

import (
	"fmt"
	"strings"
)

func main() {
	
	s := "hello world hello"
	
	ns := strings.Replace(s, "hello", "bye", 2)     // 2 occurrence of hello
	fmt.Println(ns)            // bye world bye
}

Custom replacement using the Replacer

Replacer is a struct contained inside the strings package. It provides a safe concurrent way of string replacement using goroutines. Here we will simply use the replacer to replace strings without going into concurrent programming.

To use replacer we first need to declare it. The way we create a replacer is to use the NewReplacer function.

import (
	"fmt"
	"strings"
)

func main() {
	// create using newreplacer
	re := strings.NewReplacer("C", "C++", "float", "int")
	
	s := "a float in C"
	res := re.Replace(s)
	fmt.Println(res)            // a int in C++	
}

As can be seen, all of the replacements have been replaced. This is a very handy function that can be used to do the replacement in a list of strings.