如何在最后用白色 space 替换字符串中的最后一个字符

How to replace last character in a string with white space in the end

我在java中有这种情况,字符串中的最后一个字符:-应替换为“”。

示例:

String value = "data - ";

String value2 = "data :";

value.replaceAll("[-:]$","");

value2.replaceAll("[:-]$","");

System.out.println(value);

System.out.println(value2);

输出:

data -

data

我认为空格被视为最后一个字符并且与正则表达式提供的不匹配,有人可以帮助我解决这个问题吗?谢谢。

private static String strip(String s) {
    if (s.endsWith(":") || s.endsWith("-")){
        s = s.substring(0, s.length()-1);
    }
    return s;
}

您可以使用 value.trim() 删除任何多余的空格。