欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 去空格

程序员文章站 2022-03-15 20:54:14
...

1.trim() 方法用于删除字符串的头尾空白符。

public class Test {
    public static void main(String args[]) {
        String Str = new String(" hello word ");
        System.out.println( Str );

        System.out.print("删除空格 :" );
        System.out.println(Str.trim());
    }
}

2.replace(" ", "") 去掉所有空格

public class Test {
    public static void main(String args[]) {

        String str = " hello word ";
        String str2 = str.replaceAll(" ", "");
        System.out.println(str2); 
    }
}

3.deleteWhitespace 去掉所有空格

public class Test {
    public static void main(String args[]) {

        String str = " hello word ";
        String str1 = StringUtils.deleteWhitespace(str);
        
        System.out.println(str1);
    }
}

maven下载该jar org.apache.commons.lang.StringUtils


<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.7</version>
</dependency>

源码:

  public static String deleteWhitespace(String str)
  {
    if (isEmpty(str))
      return str;

    int sz = str.length();
    char[] chs = new char[sz];
    int count = 0;
    for (int i = 0; i < sz; ++i)
      if (!(Character.isWhitespace(str.charAt(i))))
        chs[(count++)] = str.charAt(i);


    if (count == sz)
      return str;

    return new String(chs, 0, count);
  }

 

相关标签: String