Replace One Specific Character with Another in Java



Use the replace() method to replace a specific character with another. Let’s say the following is our string and here we are replacing a whitespace with a $ character.

String str1 = "Orange is the new Black!";

Now, use the replace() method to replace a character with $

str1.replace(' ', '$');

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str1 = "Orange is the new Black!";
      System.out.println("String: "+str1);
      String str2 = str1.replace(' ', '$');
      System.out.println("Updated string: "+str2);
   }
}

Output

String: Orange is the new Black!
Updated string: Orange$is$the$new$Black!
Updated on: 2020-06-25T13:26:35+05:30

554 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements