JAVA中去除String字符串中的空格

  1. 去掉首尾空格

    str.trim();

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

    str.replace(" ", "");

    例如:

    String str = " hell o "; String str2 = str.replaceAll(" ", "");
    System.out.println(str2); //输出hello(无空格)

  3. 去掉所有空格

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

  4. \s 可以匹配空格、制表符、换页符等空白字符的其中任意一个

    str.replaceAll("\\s*", "");

猜你喜欢

转载自blog.csdn.net/CrackgmKey/article/details/80106739