How to replace a word in String in Java

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.

Java - replace() method in String

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 targetThe sequence of char values to be replaced (we can say a word to be replaced)

CharSequence replacementThe 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 

1) Employee Management System using Spring Boot Microservices & React.

2) Hotel Management System using Spring Boot & React.

3) E-commerce Project using Spring Boot & React.

4) Gym Management System using Spring Boot & React.

Students can use this project for learning and can submit the project for their final year or Internship projects.

IF YOU WANT THE PROJECT DO CONTACT ME. 

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.

Or You can simply Request for the Project Source Code & Set Up by clicking on the below button.

MAIL ME AT codewithmurad@gmail.com

DM ME ON INSTAGRAM at @codewithmurad

DM ME ON FACEBOOK at @codewithmurad 

DM ME ON TELEGRAM at @codewithmurad 

Connect on My Discord Server: CLICK HERE

Post a Comment

0 Comments