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?
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.
This will work fine:
String myString = "test, test1, must not be null";
int index = myString.lastIndexOf(",");
StringBuilder sb = new StringBuilder(myString);
if(index>0) {
sb.deleteCharAt(index);
}
myString = sb.toString();
System.out.println(myString);
Can't you fix the problem upstream in the code? instead of adding a comma after each element of the list, put it in front of each element of the list except the first element. Then you don't need to resort to these hacky solutions.
Here is one option which uses a negative lookahead to target the final comma in the string:
String myString = "test, test1, must not be null";
myString = myString.replaceAll(",(?!.*,)", "");
System.out.println(myString);
test, test1 must not be null
Another solution using String
class substring()
function.
int index=str.lastIndexOf(',');
if(index==0) {//end case
str=str.substring(1);
} else {
str=str.substring(0, index)+ str.substring(index+1);
}
Try this :
int index=str.lastIndexOf(',');
if(index==0) {//end case
str=str.substring(1);
} else {
str=str.substring(0, index)+ str.substring(index+1);
}