删除java中字符串末尾的空格 [英] Removing spaces at the end of a string in java

查看:423
本文介绍了删除java中字符串末尾的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

从Java字符串中删除前导和尾随空格

当我将数据导入应用程序时,我需要删除某些字符串末尾的空格而不是开头的空格,所以我不能使用trim()...我已经设置了一个方法:

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);
    }

其中cadena是我必须转换的字符串......

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

所以,如果cadena =1234,这种方法会返回1234......

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

我想知道如果有更有效的方法来做到这一点...

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

推荐答案

你可以使用 replaceAll()<字符串上的/ code>方法,正则表达式 \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.

这篇关于删除java中字符串末尾的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆