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:
// 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.
Recommended Posts:
- math.Lgamma() Function in Golang with Examples
- math.Float64bits() Function in Golang With Examples
- atomic.AddInt64() Function in Golang With Examples
- atomic.StoreInt64() Function in Golang With Examples
- reflect.FieldByIndex() Function in Golang with Examples
- string.Contains Function in Golang with Examples
- bits.Sub() Function in Golang with Examples
- io.PipeWriter.CloseWithError() Function in Golang with Examples
- time.Round() Function in Golang With Examples
- reflect.AppendSlice() Function in Golang with Examples
- reflect.ChanOf() Function in Golang with Examples
- flag.Bool() Function in Golang With Examples
- time.Sleep() Function in Golang With Examples
- time.Time.Year() Function in Golang with Examples
- reflect.DeepEqual() Function in Golang with Examples
- reflect.Indirect() Function in Golang with Examples
- reflect.CanAddr() Function in Golang with Examples
- reflect.CanInterface() Function in Golang with Examples
- reflect.CanSet() Function in Golang with Examples
- reflect.Cap() Function in Golang with Examples
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.

