Java Program to replace all occurrences of a given character in a string


Use replace() method to replace all occurrences of a given character in a string.

Here is our string.

String str = "THIS IS DEMO LINE $$$ NEW LINE";

Let us now replace all occurrences of character $ with *

str.replace("$", "*")

The following is the complete example that replace all occurrences of $ with *

Example

 Live Demo

public class Demo {
    public static void main(String[] args) {
       String str = "THIS IS DEMO LINE $$$ NEW LINE";
       System.out.println("String = "+str);
       System.out.println("Replacing all occurrence of given character...");
       System.out.println("Updated string = "+str.replace("$", "*"));
    }
}

Output

String = THIS IS DEMO LINE $$$ NEW LINE
Replacing all occurrence of given character...
Updated string = THIS IS DEMO LINE *** NEW LINE

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements