To replace all occurrences of a substring in a string in Go, you can use the strings.ReplaceAll
function.
In this example,
str
.strings.ReplaceAll
function with the substring to be replaced, the replacement string, and the input string as arguments.strings.ReplaceAll
function returns a new string with all occurrences of the substring replaced.package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello World Hello"
newStr := strings.ReplaceAll(str, "Hello", "Hi")
fmt.Println(newStr)
}
Hi World Hi
In this example,
str
.strings.ReplaceAll
function with the character to be replaced, the replacement character, and the input string as arguments.strings.ReplaceAll
function returns a new string with all occurrences of the character replaced.package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello World Hello"
newStr := strings.ReplaceAll(str, "o", "X")
fmt.Println(newStr)
}
HellX WXrld HellX
In this tutorial, we learned How to Replace All Occurrences of a Substring in a String in Go language with well detailed examples.