dim*_*uta 9 java string spaces
可能重复:
从Java字符串中删除前导和尾随空格
当我将数据导入应用程序时,我需要摆脱某些字符串末尾的空格而不是开头的空格,所以我不能使用trim()...我已经设置了一个方法:
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);
}
Run Code Online (Sandbox Code Playgroud)
其中cadena是我必须改变的字符串......
所以,如果cadena ="1234",这种方法会返回"1234"......
我想知道是否有更有效的方法来做到这一点......
kga*_*ron 26
您可以replaceAll()在字符串上使用方法,使用正则表达式\s+$:
return cadena.replaceAll("\\s+$", "");
Run Code Online (Sandbox Code Playgroud)
如果您只想删除实际空格(不是制表符或新行),请使用\\s正则表达式中的空格替换.
String s = " this has spaces at the beginning and at the end ";
String result = s.replaceAll("\\s+$", "");
Run Code Online (Sandbox Code Playgroud)
public static String replaceAtTheEnd(String input){
input = input.replaceAll("\\s+$", "");
return input;
}
Run Code Online (Sandbox Code Playgroud)
我会这样做:
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);
}
Run Code Online (Sandbox Code Playgroud)
它比使用正则表达式更冗长,但它可能更有效。
| 归档时间: |
|
| 查看次数: |
36804 次 |
| 最近记录: |