Replace All Occurrences of a Given Character in Java



Let’s say the following is our string.

THIS IS DEMO TEXT!

Here, to replace every occurrence of ‘I’ with ‘E’, use the replace() method.

str.replace('I', 'E'));

The following is the complete example to replace all occurrences of a given character with new character.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = "THIS IS DEMO TEXT!";
      System.out.println("String = "+str);
      System.out.println("Updated string = "+str.replace('I', 'E'));
   }
}

Output

String = THIS IS DEMO TEXT!
Updated string = THES ES DEMO TEXT!
Updated on: 2020-06-25T13:21:05+05:30

400 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements