Replace Comma in String Java

Replace Comma in String Java | In Java programming language, to replace a character we can use either replace() or replaceAll() methods, which are built-in methods in the Java String class. Also see:- Remove Commas From String Java

Replace Comma in String Java using replace() Method

There are two variations in the replace() method:-

  1. public String replace(char oldChar, char newChar)
  2. public String replace(CharSequence target, CharSequence replacement)

The first replace() takes only characters and the second replace() method takes a CharSequence as a parameter.

Method Syntax:- public String replace(Char target, Char replacement)

Parameters: It takes two parameters. i) target – The char values to be replaced. ii) replacement – The replacement of char values.
Return: A replaced string.

Replace Comma in String Java Using replace(char oldChar, char newChar) Method

public class Main {
   public static void main(String args[]) {
      String string = "www,knowprogram,com";
      System.out.println(string.replace(',', '.'));
   }
}

Output:-

www.knowprogram.com

Observe the code, here comma ‘,’ character has been replaced by the dot ‘.’ character using replace() method. The replace() method finds all the commas in the given string and replace them with a dot (.) character.

Replace Comma in String Java using the replaceAll() Method

The replaceAll() method works the same as replace() method but the difference is the replace() method replaces all the occurrences of an old character with a new character while the replaceAll() method replaces all the occurrences of the old string with the new string. See more:- Java replace() vs replaceAll() Method

Method Syntax:- public String replaceAll(String regex, String replacement)

Parameters: It takes 2 parameters. i) regex – the regular expression to which this string is to be matched. ii) replacement – the string to be substituted for each match.
Return: A replaced string.
Throws: PatternSyntaxException, if the regular expression’s syntax is invalid

Replace Comma in String Java using replaceAll()

public class Main {
   public static void main(String args[]) {
      String string = "www,knowprogram,com";
      System.out.println(string.replaceAll(",", "."));
   }
}

Output:-

www.knowprogram.com

Clearly, both programs work the same even though the methods used are different.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *