Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   






Replace() FUNCTION


Replace() Function


The Replace() Function is used to replace a substring with the new one.


Example :



package main
import "fmt"
import "strings"
    
func main() {
    
    x := "Hello Beautiful World"
    y := strings.Replace(x, "Beautiful", "Wonderful", 1)
            
    fmt.Println(y)  
}


Output :



 Hello Wonderful World

In the above code, we have declared a String 'Hello Beautiful World' and assigned it to a variable 'x'.


x := "Hello Beautiful World"

java_Collections

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'.


y := strings.Replace(x, "Beautiful", "Wonderful", 1)

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,


Hello Wonderful World

java_Collections

Now, let us say, we have the below String,


"The Beautiful world is Beautiful indeed"

And you are just suppose to change the first substring 'Beautiful' with 'Wonderful'.


Something like the below,


"The Beautiful world is Beautiful indeed"

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.


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


Output :



 The Wonderful world is Beautiful indeed

So, if you see the above output, only the first occurrence of 'Beautiful' is replaced with 'Wonderful'.


That is because of the below line,


y := strings.Replace(x, "Beautiful", "Wonderful", 1)

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