从Java 8中不以逗号结尾的字符串中删除最后一个逗号

时间:2018-08-16 09:00:46

标签: java string

我输入了字符串:

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

我要删除此字符串中的最后一个逗号

预期输出:

test, test1 must not be null

您知道是否可以使用StringUtils完成此操作吗?

7 个答案:

答案 0 :(得分:15)

您也可以使用StringBuilder

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

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

您可能需要将其包装在if(myString.lastIndexOf(",") >= 0)中,以避免索引超出范围例外

答案 1 :(得分:2)

使用正则表达式,您可以使用以下示例替换最后一个,

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

实质上,它会查找逗号,后跟0个或多个非逗号字符,直到字符串结尾,然后用相同的内容替换该序列,而无需逗号。

答案 2 :(得分:2)

这可以正常工作:

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

答案 3 :(得分:1)

您不能在代码上游解决问题吗?不要在列表的每个元素之后添加逗号,而应将逗号放在列表中除第一个元素之外的每个元素之前。然后,您无需诉诸于这些骇人听闻的解决方案。

答案 4 :(得分:0)

这是一个使用否定超前来确定字符串中最后一个逗号的选项:

String myString = "test, test1, must not be null";
myString = myString.replaceAll(",(?!.*,)", "");
System.out.println(myString);

test, test1 must not be null

Demo

答案 5 :(得分:0)

使用Stringsubstring()函数的另一种解决方案。

int index=str.lastIndexOf(',');
if(index==0) {//end case
    str=str.substring(1);
} else {
    str=str.substring(0, index)+ str.substring(index+1);
}

答案 6 :(得分:0)

尝试一下:

int index=str.lastIndexOf(',');
if(index==0) {//end case
    str=str.substring(1);
} else {
    str=str.substring(0, index)+ str.substring(index+1);
}