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 :


x = "Hello Beautiful World"
y = x.replace("Beautiful", "Wonderful")
print(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 = x.replace("Beautiful", "Wonderful")

As we can see, there are two parameters in the 'replace("Beautiful", "Wonderful")' function.


And thus the substring 'Beautiful' is searched in the String, 'Hello Beautiful World'. When found, 'Beautiful' is replaced with 'Wonderful'.


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, there is a third parameter used by 'replace()' function that says how many occurrence that needs to be replaced.


Let us see with the below example.


Example :


x = "The Beautiful world is Beautiful indeed"
y = x.replace("Beautiful", "Wonderful", 1)
print(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 = x.replace("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