Java Program to replace all occurrences of given String with new one

Java 8Object Oriented ProgrammingProgramming

User replaceAll() method to replace all occurrences of a given string. Let’s say the following is our string.

String str = "THIS IS DEMO LINE AND NEW LINE!";

Here, we are replacing all occurrences of string “LINE” to “TEXT”

str.replaceAll("LINE", "TEXT");

The following is the final example.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = "THIS IS DEMO LINE AND NEW LINE!";
      Sytem.out.println("String = "+str);
      System.out.println("Replacing all occurrence of string LINE...");
      System.out.println("Updated string = "+str.replaceAll("LINE", "TEXT"));
    }
}

Output

String = THIS IS DEMO LINE AND NEW LINE!
Replacing all occurrence of string LINE...
Updated string = THIS IS DEMO TEXT AND NEW TEXT!
raja
Published on 12-Dec-2018 07:20:07
Advertisements