Several ways to remove spaces from Java strings

  1. remove leading and trailing spaces

    String str = "Hello java!  ";
    System.out.println(str.trim());
    
  2. Remove all spaces, including the middle

    String str = "Hello java!  ";
    
    String str2 = str.replaceAll(" ", "");
    System.out.println(str2);
    
  3. Replace most whitespace characters, not limited to spaces

    String str = "Hello java!  ";
    
    String str3 = str.replaceAll("\\s*","");
    System.out.println(str3);
    

    Among them, \s can match blank characters such as spaces, tabs, and form
    feeds Java regular expressions

Guess you like

Origin blog.csdn.net/ximaiyao1984/article/details/132326100