How to replace string with another string in java Program

public class ReplaceAllExample2 {
  public static void main(String args[]) {
    String s1 = "My name is Rajendra. My name is Sarvam. My name is TechSarvam.";
    String replaceString = s1.replaceAll("is", "was"); //replaces all occurrences of "is" to "was"
    System.out.println(replaceString);
  }
}

Step-by-Step Breakdown:

1. Class and Method Declaration:

public class ReplaceAllExample2 

{

    public static void main(String args[]) 

    {

  • The program declares a class ReplaceAllExample2.
  • The main method is the entry point where execution begins.

2. String Declaration:

String s1 = “My name is Rajendra. My name is Sarvam. My name is TechSarvam.”;

A String variable s1 is declared and assigned the string value “My name is Rajendra. My name is Sarvam. My name is TechSarvam.”

3. Using replaceAll() Method:

String replaceString = s1.replaceAll(“is”, “was”);

The call to the method replaceAll(“is”, “was”) will replace all occurrences of the string “is” with the string “was”.

The replaceAll() method takes two arguments:

  • The first argument: The string to be replaced (in this case, “is”).
  • The second argument: The string to replace the first one (in this case, “was”).
  • The method will find the entire string s1 and replace all its occurrences of “is” with “was”, wherever it may occur.

4. Printing the Result:

System.out.println(replaceString);

It will print out the modified string in the variable replaceString, which is the result of all “is”s replaced by “was”.

Example Explanation:

The input string s1 is:

” My name is Rajendra. My name is Sarvam. My name is TechSarvam.”

The replacement of words “is” and “was” through replaceAll(“is”, “was”) will replace the following lines.

  • “is”  from “is Rajendra” to  “was”  and gets converted to  “was Rajendra”.
  • “is”  from “is Sarvam” to  “was”  and gets converted to  “was Sarvam”.
  • “is” in “is TechSarvam” with “was”, so it becomes “was TechSarvam”.

Thus, the modified string will be:

“My name was Rajendra. My name was Sarvam. My name was TechSarvam.”

Program Output:

My name was Rajendra. My name was Sarvam. My name was TechSarvam.

Summary:

  • The function places all instances of the substring “is” in the original string s1 with the substring “was”.
  • The replaceAll() method is sensitive to case, therefore it will only replace the lowercase “is” and not “Is”, “IS” and the rest.

Leave a Comment

Your email address will not be published. Required fields are marked *