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

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 12-Dec-2018 07:24:16
Advertisements