Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove comma if string having comma at end [duplicate]

Tags:

java

string

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 ","

like image 355
user1071753 Avatar asked Feb 15 '12 11:02

user1071753


People also ask

How do you remove the last comma from a comma separated string?

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.

How do you remove all commas in a 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.


1 Answers

You could try a regular expression:

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

Or a simple substring:

if (names.endsWith(",")) {   names = names.substring(0, names.length() - 1); } 
like image 51
Dave Webb Avatar answered Sep 28 '22 04:09

Dave Webb