Kushal Shah Kushal Shah - 3 months ago 15x
Java Question

Remove trailing comma from comma-separated string

I got String from the database which have multiple commas (

) . I want to remove the last comma but I can't really find a simple way of doing it.

What I have:
kushalhs, mayurvm, narendrabz,

What I want:
kushalhs, mayurvm, narendrabz


The best way is probably to use

str = str.replaceAll(", $", "");

This also handles the empty list (empty string) gracefully, as opposed to lastIndexOf / substring solutions which requires special treatment of such case.

Example snippet:

String str = "kushalhs, mayurvm, narendrabz, ";
str = str.replaceAll(", $", "");
System.out.println(str);  // prints "kushalhs, mayurvm, narendrabz"