Java - replace() method in String
In this tutorial, we will learn how to replace a word in a string in Java.
For replacing a word in String in Java, we have got a method called replace() method which is present in the String class as we can see in the below picture.
ABOUT REPLACE() METHOD
Syntax:
public String replace(CharSequence target, CharSequence replacement)
The method replace(CharSequence target, CharSequence replacement) is present inside the class String which is present inside java.lang package.
Parameters Details:
CharSequence target: The sequence of char values to be replaced (we can say a word to be replaced)
CharSequence replacement: The replacement sequence of char values (we can say replacement word, a word which is to be replaced with)
Returns:
It returns a Sting derived from our main String by replacing an old word with a new word.
Example:
public class ReplaceDemo {
public static void main(String[] args) {
String originalString = "Programming With Murad";
String stringAfterWordReplacement = mainString.replace("Programming", "Code"); // line 1
System.out.println("Original String: "+mainString);
System.out.println("String after word replacement: "+stringAfterWordReplacement);
}
}
The output of the program:
Original String: Programming With Murad
String after word replacement: Code With Murad
Note: If the char sequence or word does not occur in the original String, then the same original String object is returned.
So let us suppose, in the above program if we use
String stringAfterWordReplacement = mainString.replace("Learn", "Code");
at line 11
Then our output will be:
Original String: Programming With Murad
String after word replacement: Programming With Murad
I hope that you find this article useful. I'll love to hear from you. Let me know if you have any questions about replace() method in String in Java.
FINAL YEAR PROJECTS
Online Watch Shopping Project with PAYPAL integrated
(click on it to read more about the project )
Other practical projects using React & Spring Boot
I will give you the full project SOURCE CODE and I will do a COMPLETE SET-UP of the project on your PC or Laptop remotely.
MAIL ME AT mjmuradali31@gmail.com
DM ME ON INSTAGRAM at @muradalimj
DM ME ON FACEBOOK at Murad Ali
DM ME ON TELEGRAM at @muradalimj
Connect on My Discord Server: CLICK HERE
-----------------------------------------------------------------------------------------------------------------------------
CODE WITH MURAD
0 Comments