Replace. Sometimes a string has characters we do not want. We can replace these substrings with other strings. In Go the strings package is helpful.
For simple replacements, we use strings.Replace. One or many occurrences can be targeted. For more complex sets of replacements we use a Replacer.
This example uses the "strings" package and the strings.Replace func, which receives 4 arguments. It replaces all occurrences of a substring with another one.
Argument 1 This is the string we want to perform replacements upon. The strings.Replace func returns a modified version of this string.
Argument 2 The second argument is the before string, and since we want to replace "at" with something else, we pass "at."
Argument 3 This is the after string—the string we want to be included in place of the before string.
Argument 4 The final argument is the occurrence count to replace. We pass -1 as the occurrence count, so all instances are replaced.
package main
import (
"fmt""strings"
)
func main() {
value := "cat"
fmt.Println(value)
// Replace the "cat" with a "calf."
result := strings.Replace(value, "at", "alf", -1)
fmt.Println(result)
}cat
calf
Count argument. We continue with a similar example of strings.Replace. The fourth argument here is positive 1. So only the first match is replaced—then the method stops.
Tip Use the value -1 to mean "global replace" and a positive integer to replace a certain number of matches.
package main
import (
"fmt""strings"
)
func main() {
value := "bird bird bird"// Use a positive number to indicate max replacement count.
result := strings.Replace(value, "bird", "fish", 1)
fmt.Println(result)
}fish bird bird
Replacer. This is a class available in the "strings" package. We create a Replacer with the strings.NewReplace method. We pass string pairs to NewReplace.
Tip The arguments to NewReplace are in the form of before and after strings, one after another, in pairs.
Detail We invoke Replace() on the Replacer to apply all strings replacements. In this example, 3 strings are replaced.
package main
import (
"fmt""strings"
)
func main() {
value := "bird, cat and fish"// Create replacer with pairs as arguments.
r := strings.NewReplacer("bird", "dog",
"cat", "lion",
"fish", "monkey")
// Replace all pairs.
result := r.Replace(value)
fmt.Println(result)
}dog, lion and monkey
Replacer versus replace. Is Replacer faster than strings.Replace? In my benchmark, I found that there is a cost to creating a Replacer instance.
Version 1 This version of the code uses the Replacer class to replace substrings in a string.
Version 2 This code uses the strings.Replace multiple times to replace all the needed substrings.
Result For repeated usage, a Replacer is faster than many calls to strings.Replace. But there is some complexity here.
Info If you have only a couple Replaces to do, creating a Replacer will end up costing more. For larger tasks, Replacer is superior.
package main
import (
"fmt""strings""time"
)
func main() {
original := "cat and dog"// Create Replacer (excluded from benchmark time).
r := strings.NewReplacer("cat", "car",
"and", "or",
"dog", "truck")
t0 := time.Now()
// Version 1: use Replacer.
for i := 0; i < 1000000; i++ {
result := r.Replace(original)
if result != "car or truck" {
fmt.Println(0)
}
}
t1 := time.Now()
// Version 2: use Replace calls.
for i := 0; i < 1000000; i++ {
temp := strings.Replace(original, "cat", "car", -1)
temp = strings.Replace(temp, "and", "or", -1)
result := strings.Replace(temp, "dog", "truck", -1)
if result != "car or truck" {
fmt.Println(0)
}
}
t2 := time.Now()
// Results.
fmt.Println(t1.Sub(t0))
fmt.Println(t2.Sub(t1))
}624.437ms , Replacer
805.5738ms, strings.Replace
Summary. With strings.Replace we can replace one or more instances of substrings. And with Replacer, we have a powerful type that can combine many replacements.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 10, 2025 (rewrite).