How to use strings.Replace() in Golang
The Golang strings.Replace() method
The Go programming language, or Golang, provides a string package that contains various functions for manipulating UTF-8 encoded strings.
One of these functions is the Replace() method.
In Golang, the strings.Replace() function returns a copy of the given string, with the first n non-overlapping instances of the old string replaced with the new one.
Syntax
func Replace(s, old str, new str, n int) string
Parameter
s: This is the given string.old: This is the string to be replaced.new: This is the string that replaces the old one.n: This is the number of times the old string is replaced.
Note: If the old string is empty, it matches at the start of the string. After each UTF-8 sequence, it yields up to k+1 replacements, giving a k-rune string. There is no limit to how many replacements can be made if
nis less than zero.
To use the string package’s functions, we must use the import keyword to import a string package into our program.
package main
import (
"fmt"
"strings"
)
Code
The following code shows how to implement the strings.Replace() method in Golang.
// Golang program// Strings.Replace() functionpackage main// Accessing the string package's functionimport ("fmt""strings")func main() {// Using the Replace() function//Replacing the first 3 matched substring m with Mfmt.Println(strings.Replace("my name is maria marris", "m", "M", 3))//Replacing every matched substring j with Jfmt.Println(strings.Replace("john joe job jona jonathan", "j", "J", -1))}
What happens if we omit the old parameter?
Let’s now take a look at another example without the old value.
// Golang program// Using the strings.Replace() function without the old parameterpackage mainimport ("fmt""strings")func main() {// Using the functionfmt.Println(strings.Replace("my name is maria marris", "", "M", 3))fmt.Println(strings.Replace("john joe job jona jonathan", "", "J", -1))}
Explanation
In the above code, every alternate position is replaced n times by the new string.