Removing spaces at the end of a string in java

diminuta picture diminuta · Aug 24, 2012 · Viewed 42.1k times · Source

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...

Answer

kgautron picture kgautron · Aug 24, 2012

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.