How to Replace Substrings in a String in Go
In Go, you can replace parts of a string using the
strings.Replace function from the strings package. It takes the original string, the substring to replace, the replacement string, and the number of replacements to make. Use -1 to replace all occurrences.Syntax
The strings.Replace function has this syntax:
func Replace(s, old, new string, n int) string
Where:
sis the original string.oldis the substring you want to replace.newis the string to replaceoldwith.nis the number of replacements to make. Use-1to replace all occurrences.
go
package main import ( "fmt" "strings" ) func main() { result := strings.Replace("hello world", "world", "Go", 1) fmt.Println(result) }
Output
hello Go
Example
This example shows how to replace all occurrences of a substring in a string using strings.Replace. It replaces "cat" with "dog" everywhere in the text.
go
package main import ( "fmt" "strings" ) func main() { text := "the cat sat on the cat mat" newText := strings.Replace(text, "cat", "dog", -1) fmt.Println(newText) }
Output
the dog sat on the dog mat
Common Pitfalls
One common mistake is forgetting that strings in Go are immutable, so strings.Replace returns a new string and does not change the original. Another is using n incorrectly; setting it to 1 replaces only the first occurrence, not all.
Also, replacing an empty string "" can lead to unexpected results.
go
package main import ( "fmt" "strings" ) func main() { original := "hello world" // Wrong: expecting original to change strings.Replace(original, "world", "Go", 1) fmt.Println(original) // prints "hello world" // Right: assign the result newStr := strings.Replace(original, "world", "Go", 1) fmt.Println(newStr) // prints "hello Go" }
Output
hello world
hello Go
Quick Reference
| Parameter | Description |
|---|---|
| s | Original string to search in |
| old | Substring to find and replace |
| new | Substring to replace with |
| n | Number of replacements (-1 means all) |
Key Takeaways
Use strings.Replace to create a new string with replacements; original string stays unchanged.
Set n to -1 to replace all occurrences of the substring.
Always assign the result of strings.Replace to a variable to keep changes.
Replacing an empty string "" can cause unexpected behavior, so avoid it.
Import the strings package to use strings.Replace.