Java 去除字符串中的空白字符

Java 去除字符串中的空白字符

通过String的trim()方法只能去掉字符串两端的空格字符,但是对于\t \n等其它空白字符确不能去掉,因此需通过正则表达式,将其中匹配到的空白字符去掉,代码如下:

1

2

3

4

5

6

7

8

9

10

11

protected String replaceBlank(String str){

       String dest = null;

       if(str == null){

           return dest;

       }else{

           Pattern p = Pattern.compile("\\s*|\t|\r|\n| ");

           Matcher m = p.matcher(str);

           dest = m.replaceAll("");

           return dest;

       }

   }

猜你喜欢

转载自blog.csdn.net/Zsigner/article/details/83714580