Open In App

strings.NewReplacer() Function in Golang With Examples

Improve
Improve
Like Article
Like
Save
Share
Report

strings.NewReplacer() Function in Golang returns a new Replacer from a list of previous, new string sets. Substitutions are performed within the order they show up within the target string, without overlapping matches. The old string comparisons are done in argument order. The old string comparisons are done in argument order.

Syntax

func NewReplacer(oldnew ...string) *Replacer

Remember NewReplacer panics if given an odd number of arguments.

Example 1:




// Golang program to illustrate the
// strings.NewReplacer() Function
package main
  
import (
    "fmt"
    "strings"
)
  
func main() {
    r := strings.NewReplacer("<", "<", ">", ">")
    fmt.Println(r.Replace("Hey I am <b>GFG</b>!"))
}


Output:

Hey I am <b>GFG</b>!

Example 2:




// Golang program to illustrate the
// strings.NewReplacer() Function
package main
  
import (
    "fmt"
    "strings"
)
  
// Main function
func main() {
  
    // using the function
    r := strings.NewReplacer("(", "easy", ")", "tough;")
    fmt.Println(r.Replace("The dsa course of geeksforgeeks is ( not )"))
}


Output:

The dsa course of geeksforgeeks is easy not tough;

Last Updated : 10 May, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads