方式一
public static void main(String[] args) {
String str = " abc def ghi mnopq r s ";
StringTokenizer pas = new StringTokenizer(str, " ");
str = "";
while (pas.hasMoreTokens()) {
String s = pas.nextToken();
str = str + s + " ";
}
System.out.println("[" + str.trim() + "]");
}
[abc def ghi rrr r s]
方式二
public static void main(String[] args) {
String str = " h r l h . ";
System.out.println("str =[" + str + "]");
String newStr = str.replaceAll(" + ", " ");
System.out.println("newStr ——[" + newStr.trim() + "]");
}
str =[h r l h .]
newStr ——[h r l h .]
方式三
public static void main(String[] args) {
String str = " h r l h . ";
System.out.println("str =[" + str + "]");
String newStr = repaceWhiteSapce(str);
System.out.println("newStr ——[" + newStr.trim() + "]");
}
public static String repaceWhiteSapce(String original) {
StringBuilder sb = new StringBuilder();
boolean isFirstSpace = false;
original = original.trim();
char c;
for (int i = 0; i < original.length(); i++) {
c = original.charAt(i);
if (c == ' ' || c == '\t') {
if (!isFirstSpace) {
sb.append(c);
isFirstSpace = true;
}
} else {
sb.append(c);
isFirstSpace = false;
}
}
return sb.toString();
}
str =[ h r l h . ]
newStr ——[h r l h .]
|