java去除末尾空格,删除java中字符串末尾的空格

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 cant use trim()... Ive 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"...

Id like to know if theres a more efficient way to do this...

解决方案

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.

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 cant use trim()... Ive 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"... Id like to know if theres a more efficient way to do this... 解决方案 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.
经验分享 程序员 微信小程序 职场和发展