如:"aa bb cc dd ee ff"变成"aa bb cc dd ee ff"
正则表达式实现
String string = "aa bb cc dd ee ff" String test = string.replaceAll("\\s{1,}", " "); System.out.println(test); string = test; String[] str = string.split(" "); for (String string2 : str) { System.out.println(string2); }
用循环实现
String str = "aa bb cc dd ee ff"; String s = ""; for (int i = 0; i < str.length() - 1; i++) { //空格转成int型代表数字是32 if ((int) str.charAt(i) == 32 && (int) str.charAt(i + 1) == 32) { continue; } s += str.charAt(i); } if ((int) str.charAt(str.length() - 1) != 32) s += str.charAt(str.length() - 1); System.out.println(s);