Open In App

strings.Replace() Function in Golang With Examples

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

strings.Replace() Function in Golang is used to return 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 string 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:




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


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.




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


Output:

GiG GaGmG geeks
FiF FlFoFvFeF FtFhFeF FgFeFeFkFiFnFeFsFsF

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



Last Updated : 05 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads