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:
package main
import (
"fmt"
"strings"
)
func main() {
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.
package main
import (
"fmt"
"strings"
)
func main() {
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
05 Aug, 2022
Like Article
Save Article