How to remove last comma from a string in Java

In this tutorial, we will learn how to remove the last comma from a given string in Java. Suppose we have a string that ends with a comma or a user inputs a string ending with a comma, and while displaying the output we would like to ignore it, So what do we do?

For this to happen let us first study the replaceAll() string method, which is one of the techniques to remove the last comma from a given string, let’s start…

Remove the last comma: replaceAll() method

In java, the replaceAll() method can be used to replace all the occurrence of a single character, or a substring from a given string. The replaceAll() method belongs to the java.lang.String class.

The replaceAll() method takes two parameters.,

  1. Initial: The character/substring that has to be replaced.
  2. Updated: The character/substring used to replace the initial string.

Syntax:

public String replaceAll(String initial, String updated);

Here, public is an access modifier, meaning the method can be accessed from other classes in Java., this may be ignored.
We pass the characters of the string that needs to be replaced with the updated character.

Let us see an example..,

import java.util.*;
import java.lang.*;
public class comma 
{
   public static void main(String []args)
   {
     String str="h,e,l,l,o,";
     System.out.println(str.replaceAll(",$",""));
   }
}

Output:

h,e,l,l,o

As we can see in the above example we have specified a “$” after the comma which indicates the end of the string. Suppose we don’t specify the “$” after the comma, then all the commas in the original string would be removed., this is shown below…

import java.util.*;
import java.lang.*;
public class comma 
{
   public static void main(String []args)
   {
     String str="h,e,l,l,o,";
     System.out.println(str.replaceAll(",",""));
   }
}

Output:

hello

So the above examples give us one of the methods of removing comma from the end of the strings.

You may also read,

Leave a Reply

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