strings.Replace() Function in Golang With Examples

strings.Replace() Function in Golang is used to returns a copy of the given string with the first n non-overlapping instances of old replaced by new one.

Syntax:

func Replace(s, old, new string, n int) string

Here, s is the original or given string, old is the string that you want to replace. new is the which replaces the old, and n is the number of times the old replaced.

Note: If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string. If n < 0, there is no limit on the number of replacements.

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate the usage of
// strings.Replace() function
  
package main
  
import (
    "fmt"
    "strings"
)
  
func main() {
    // using the function
    fmt.Println(strings.Replace("gfg gfg gfg", "g", "G", 3))
    fmt.Println(strings.Replace("gfg gfg gfg", "fg", "FG", -1))
}

chevron_right


Output:

GfG Gfg gfg
gFG gFG gFG

In the first case, the first 3 matched substrings of “g” in “gfg gfg gfg” get replaced by “G”. In the second case, every matched case of “fg” gets replaced by “FG”.

Example 2: Let’s consider an example where we do not pass any value for old.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate the usage of
// strings.Replace() function
  
package main
  
import (
    "fmt"
    "strings"
)
  
func main() {
  
    // using the function
    fmt.Println(strings.Replace("i am geeks", "", "G", 5))
    fmt.Println(strings.Replace("i love the geekiness", "", "F", -1))
}

chevron_right


Output:

GiG GaGmG geeks
FiF FlFoFvFeF FtFhFeF FgFeFeFkFiFnFeFsFsF

It can be seen that every alternate position gets replaced by new, n times.




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.