In Golang, you can use the strings.ReplaceAll()
function to replace all occurrences of a substring in a string. Here's how you can do it:
package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello, World! Hello, Go!"
oldSubstr := "Hello"
newSubstr := "Hi"
// Replacing all occurrences of a substring
result := strings.ReplaceAll(str, oldSubstr, newSubstr)
fmt.Println(result)
}
Output:
Hi, World! Hi, Go!
In the example above, we have a string str
containing the phrase "Hello, World! Hello, Go!". We want to replace all occurrences of the substring "Hello" with "Hi". We use the strings.ReplaceAll()
function to achieve this. The function takes three arguments: the original string, the substring to be replaced, and the replacement substring. It returns a new string with all occurrences of the old substring replaced by the new substring. The resulting string is then printed to the console.