2

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?

HugoTeixeira
  • 4,674
  • 3
  • 22
  • 32
Sahil
  • 245
  • 5
  • 11
  • 1
    For the next time: questions that show *your own* effort to solve the problem are simply more appreciated than those "here are requirements" that implicitly expect that other people do the work for you. – GhostCat Aug 16 '18 at 09:18

7 Answers7

15

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

ernest_k
  • 44,416
  • 5
  • 53
  • 99
2

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.

assylias
  • 321,522
  • 82
  • 660
  • 783
2

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);
Jayesh Choudhary
  • 748
  • 2
  • 12
  • 30
1

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.

Paul Janssens
  • 622
  • 3
  • 9
  • The last comma which the OP wants to remove is not a dangling final comma, implying that bad concatenation happened. Rather, it seem to be part of the data. – Tim Biegeleisen Aug 16 '18 at 09:33
0

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

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

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);
}
Tanmay Awasthi
  • 69
  • 1
  • 2
  • 8
0

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);
}