1 . 多个空格替换为一个,并去除开头和结尾的空格。
input = input.replaceAll("\\s+", " ").trim();
2 . split()
函数会默认忽略字符串结尾的空格,但不会忽略字符串开头和中间的所有空格,也不会将开头和中间的空格合并成一个。
String input = " s a b ";
String[] result = input.split(" ");
System.out.println(result.length);
s前面有3个空格,a前面有1个空格,b前面有2个空格,最终输出为7。