strings.NewReplacer() Function in Golang With Examples

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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>!"))
}

chevron_right


Output:

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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 )"))
}

chevron_right


Output:

The dsa course of geeksforgeeks is easy not tough;
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.