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

最后都变了- 提交于 2019-12-05 19:22:11

问题


Possible Duplicate:
Strip Leading and Trailing Spaces From Java String

When I import data to an application I need to get rid of the spaces at the end of certain strings but not those at the beginning, so I can't use trim()... I've set up a method:

public static String quitarEspaciosFinal(String cadena) {
    String[] trozos = cadena.split(" ");
    String ultimoTrozo = trozos[trozos.length-1];
    return cadena.substring(0,cadena.lastIndexOf(ultimoTrozo.charAt(ultimoTrozo.length()-1))+1);
    }

where cadena is the string I have to transform...

So, if cadena = " 1234 " this method would return " 1234"...

I'd like to know if there's a more efficient way to do this...


回答1:


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.




回答2:


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



回答3:


Apache Commons library has the appropriate method stripEnd.




回答4:


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



回答5:


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.



来源:https://stackoverflow.com/questions/12106757/removing-spaces-at-the-end-of-a-string-in-java

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