I want to remove comma at end if string ends with comma
For example
String names = "A,B,C,"
i need to remove last comma if string ends with ","
Using the substring() method We remove the last comma of a string by using the built-in substring() method with first argument 0 and second argument string. length()-1 in Java. Slicing starts from index 0 and ends before last index that is string.
To remove all commas from a string: Call the replaceAll() method, passing it a comma as the first parameter and an empty string as the second. The replaceAll method returns a new string with all matches replaced by the provided replacement.
You could try a regular expression:
names = names.replaceAll(",$", "");
Or a simple substring:
if (names.endsWith(",")) { names = names.substring(0, names.length() - 1); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With