How To Replace Substring in A String in Go?
How To Replace Substring in A String in Go?
To replace a substring in string with a new value in Go programming, we can use either Replace function or
ReplaceAll function of the strings package.
Replace function replaces only specified N occurrences of the substring, while ReplaceAll function
replaces all the occurrences of given substring with the new value.
Replace function returns a new string with the first n occurrences of replace string replaced with
newValue string in str string.
ReplaceAll function returns a new string with all occurrences of replace string replaced with
newValue string in str string.
Examples
Let us go through some of the examples using Replace and ReplaceAll functions.
Replace
In the following example, we take a string, str and replace first 2 occurrences of the substring replace
with a new value newValue .
example.go
example.go
package main
import (
"fmt"
"strings"
)
func main() {
str := "Abc Abc Abc Abc Abc"
replace := "Abc"
newValue := "Mnop"
n := 2
result := strings.Replace(str, replace, newValue, n)
fmt.Println("Original String : ", str)
fmt.Println("Result String : ", result)
}
Output
As specified via n , only the first two occurrences have been replaced.
Now, let us set n with -1 . All the occurrences of the replace string must be replaced with the new
value.
example.go
package main
import (
"fmt"
"strings"
)
func main() {
str := "Abc Abc Abc Abc Abc"
replace := "Abc"
newValue := "Mnop"
n := -1
result := strings.Replace(str, replace, newValue, n)
fmt.Println("Original String : ", str)
fmt.Println("Result String : ", result)
}
Output
In the following example, we take a string, str and replace all the occurrences of the substring replace
with a new value newValue .
example.go
package main
import (
"fmt"
"strings"
)
func main() {
str := "Abc Abc Abc Abc Abc"
replace := "Abc"
newValue := "Mnop"
result := strings.ReplaceAll(str, replace, newValue)
fmt.Println("Original String : ", str)
fmt.Println("Result String : ", result)
}
Output
All the occurrences of the given substring are replaced with new value.
Conclusion
In this Golang Tutorial, we learned how to replace a substring with new value in a string, in Go programming
language, with the help of example programs.
Golang
✦ Golang Tutorial
✦ Golang If Else
✦ Golang Switch
✦ Golang Comments
✦ Golang Comments
✦ Golang Functions
✦ Golang Array
✦ Golang Slice
✦ Golang Struct
✦ Golang Class
✦ Golang Range
✦ Golang Map
✦ Golang Goroutine
✦ Golang Channel