Java Program to replace one specific character with another

Java 8Object Oriented ProgrammingProgramming

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!
raja
Published on 06-Dec-2018 12:03:49
Advertisements