java去掉空格

来源:互联网 发布:五钻淘宝店铺值多少钱 编辑:程序博客网 时间:2024/06/08 16:49

1、去掉首尾空格

    String.trim();

2、去掉所有空格,首尾、中间

  2.1 str.replace("  ","");

      例子:

      String str = " hell o ";   
      String str2 = str.replaceAll(" ", "");   
      System.out.println(str2);  

  2.2 str.replaceAll(" +","");

3、替换大部分空白字符, 不限于空格

    str =str .replaceAll("\\s*", "");  \s 可以匹配空格、制表符、换页符等空白字符的其中任意一个 

4、自己写方法。可以去掉所有空格,包括首尾、中间

         while(position<resource.length())   
        {   
            currentChar=resource.charAt(position++);   
            if(currentChar!=ch) buffer.append(currentChar); } return buffer.toString();   
        }  

原创粉丝点击