Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove last comma from string that doesn't end with comma in Java 8 [duplicate]

Tags:

java

string

I have input string:

String myString = "test, test1, must not be null";

I want to remove last comma in this string

Expected output:

test, test1 must not be null

Any idea if this can be done using StringUtils?

like image 908
Sahil Avatar asked Apr 18 '26 15:04

Sahil


2 Answers

You can also use a StringBuilder:

String result = new StringBuilder(myString)
    .deleteCharAt(myString.lastIndexOf(",")).toString()

//"test, test1 must not be null" is the result

You may need to wrap that in if(myString.lastIndexOf(",") >= 0) to avoid index out of bounds exceptions

like image 111
ernest_k Avatar answered Apr 21 '26 03:04

ernest_k


With a regex, you can replace the last , using this for example:

String result = myString.replaceAll(",([^,]*)$", "$1");

In substance, it looks for a comma, followed by 0 or more non comma characters until the end of the string and replaces that sequence with the same thing, without the comma.

like image 34
assylias Avatar answered Apr 21 '26 04:04

assylias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!