The Replace() Function is used to replace a substring with the new one.
package main import "fmt" import "strings" func main() { x := "Hello Beautiful World" y := strings.Replace(x, "Beautiful", "Wonderful", 1) fmt.Println(y) }
In the above code, we have declared a String 'Hello Beautiful World' and assigned it to a variable 'x'.
And we would be replacing 'Beautiful' with 'Wonderful', from the String, 'Hello Beautiful World'.
So, we have used the 'replace()' Function to replace 'Beautiful' with 'Wonderful'.
As we can see, there are 4 parameters in the 'Replace(x, "Beautiful", "Wonderful", 1)' function.
And thus the substring 'Beautiful' is searched in the String, 'Hello Beautiful World'. When found, 'Beautiful' is replaced with 'Wonderful'. And '1' means exactly 1 occurrence of the substring 'Beautiful' is replaced with 'Wonderful'(We will understand it later in this tutorial).
And the new String becomes,
Now, let us say, we have the below String,
And you are just suppose to change the first substring 'Beautiful' with 'Wonderful'.
Something like the below,
To solve this, we will make use of the fourth parameter used by 'Replace()' function that says how many occurrence that needs to be replaced.
Let us see with the below example.
package main import "fmt" import "strings" func main() { x := "The Beautiful world is Beautiful indeed" y := strings.Replace(x, "Beautiful", "Wonderful", 1) fmt.Println(y) }
So, if you see the above output, only the first occurrence of 'Beautiful' is replaced with 'Wonderful'.
That is because of the below line,
Where we have specified the third parameter as '1'.
Which says that only replace 1 occurrence of the word 'Beautiful'.
And thus we got the output,
The Beautiful world is Beautiful indeed