Removing spaces at the end of a string in java [duplicate]

余生颓废 提交于 2019-12-04 04:00:23

You can use replaceAll() method on the String, with the regex \s+$ :

return cadena.replaceAll("\\s+$", "");

If you only want to remove real spaces (not tabulations nor new lines), replace \\s by a space in the regex.

    String s = "   this has spaces at the beginning and at the end      ";
    String result = s.replaceAll("\\s+$", "");

Apache Commons library has the appropriate method stripEnd.

 public static String replaceAtTheEnd(String input){
    input = input.replaceAll("\\s+$", "");
    return input;
}

I'd do it like this:

public static String trimEnd(String s)
{
    if ( s == null || s.length() == 0 )
        return s;
    int i = s.length();
    while ( i > 0 &&  Character.isWhitespace(s.charAt(i - 1)) )
        i--;
    if ( i == s.length() )
        return s;
    else
        return s.substring(0, i);
}

It's way more verbose than using a regular expression, but it's likely to be more efficient.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!