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


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!

Updated on: 26-Jun-2020

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements