方式一
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 .]
package com.szzj.gvb.op.facade.utils;
import java.util.StringTokenizer;
public class StrSplitUtil {
public static String replaceCompact(String str, String separator) {
StringTokenizer splitSpace = new StringTokenizer(str, separator);
String strSpace = "";
while (splitSpace.hasMoreTokens()) {
strSpace += splitSpace.nextToken();
}
return strSpace.trim();
}
public static String replaceInterval(String str, String separator) {
StringTokenizer subComma = new StringTokenizer(str, separator);
String strComma = "";
while (subComma.hasMoreTokens()) {
strComma += subComma.nextToken() + separator;
}
return checkEndWithSeparator(strComma.trim(), separator);
}
public static String checkEndWithSeparator(String str, String separator) {
String subStr = "";
if (str.endsWith(separator)) {
subStr = str.substring(0, str.lastIndexOf(separator));
checkEndWithSeparator(subStr, separator);
}
return subStr;
}
}