Kushal Shah Kushal Shah - 1 year ago 123
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

Answer Source

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"