Replace All Occurrences of a Given Character in a String in Java



In this article, we will learn to replace all occurrences of a given character in a string in Java.

Replace() method

The replace() method in Java is used to replace all occurrences of a given character in a string with another character. In this example, we will replace all occurrences of the character $ with *. Use the replace() method to replace all occurrences of a given character in a string.

Problem Statement

Given a string, replace all occurrences of a specific character with another character in Java. Below is the demonstration of the same ?

Input

THIS IS DEMO LINE $$$ NEW LINE

Output

THIS IS DEMO LINE *** NEW LINE

Steps to replace all occurrences of a given character in a string

Below are the steps to replace all the occurrences of a given character in a string -

  • Define a string variable str with the initial string value.
  • Print the original string.
  • Use the replace() method to replace all occurrences of the character $ with *.
  • Print the updated string.

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

Below is the Java program to replace all occurrences of a given character in a string -

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

Code Explanation

This Java program uses the replace() method to replace all occurrences of a given character in a string. The string is "THIS IS DEMO LINE $$$ NEW LINE" and we want to replace all occurrences of the character $ with *. First, we define a string variable str and assign it the value "THIS IS DEMO LINE $$$ NEW LINE".

Then, we print the original string to the console. Next, we print a message indicating that we're replacing all occurrences of the given character. Finally, we use the replace() method to replace all occurrences of $ with _ and print the updated string to the console. The replace() method takes two arguments: the character to be replaced and the character to replace it with. When we run this program, it outputs the original string, a message, and the updated string with all occurrences of $ replaced with _.

Updated on: 2024-11-19T18:23:54+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements