Remove Commas From String Java

Remove Commas From String Java | To remove all commas from the given string in Java we have several built-in methods available in the java library like delete(), replace(), and replaceAll(). These methods help in different ways to remove or delete the character or substring from the given string. Also see:- Replace Comma in String Java

Remove Commas From String Java using replace()

The Java string class contains two overloaded forms of the replace() method:-

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

Among them the second replace() method is useful for us to remove commas from string Java. Method Syntax:- public String replace(CharSequence target, CharSequence replacement)

  • Parameter:- target – The sequence of char values to be replaced; replacement:-The replacement sequence of char values
  • Return:- The resultant string after replacement.

While calling replace(CharSequence target, CharSequence replacement) method if we pass empty string ("") as the second parameter then the first parameter will be removed from the string.

Program to remove commas from string Java using replace()

public class Main {
   public static void main(String[] args) {
      String string = "Know,Program Java,Programming";
      System.out.println(string.replace(",", ""));
   }
}

Output:-

KnowProgram JavaProgramming

The above method replace() takes two-character sequence parameters target and replacement, the target is the character needed to be replaced and the replacement is a character to be placed which returns a string after replacement. 

Remove Commas From String Java Using replaceAll()

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

  • Parameter:- regex – the regular expression to which this string is to be matched; replacement – the string to be substituted for each match.
  • Return:- The resulting String.
  • Throws:- PatternSyntaxException – if the regular expression’s syntax is invalid.
public class Main {
   public static void main(String[] args) {
      String string = "Know,Program Java,Programming";
      System.out.println(string.replaceAll(",", ""));
   }
}

Output:-

KnowProgram JavaProgramming

The replaceAll() method also works very similarly to the replace() method. When we pass an empty string as the second parameter to the replaceAll() method then the first parameter is removed from the string.

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.