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?
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
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.
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