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.
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.
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.
GiG GaGmG geeks FiF FlFoFvFeF FtFhFeF FgFeFeFkFiFnFeFsFsF
It can be seen that every alternate position gets replaced by new, n times.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.