像这样的东西?
private void doTrim(String str) throws Exception {
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new StringReader(str));
String line;
String NL = System.getProperty("line.separator");
while( (line=reader.readLine())!=null ) {
sb.append(line.trim());
sb.append(NL);
}
System.out.println(">>" + str + "<<");
str = sb.toString().trim();
System.out.println(">>" + str + "<<");
}
或硬核版本循环字符串字符并更新新缓冲区。这会将尾随窗口 "\r\n" 修剪为 unix "\n" 换行符。可以避免小的 idxTail 优化 newBuf 并且只使用 buf[]。
private String trimLeadingAndTrailingSpaces(String str) {
char[] buf = str.toCharArray();
char[] newBuf = new char[buf.length];
int newCount=0;
boolean isBegin=true;
int trailingSpaces=0;
for(int idx=0; idx<buf.length; idx++) {
char ch = buf[idx];
if (isBegin) {
if (ch!=' ') {
isBegin=false;
newBuf[newCount]=ch;
newCount++;
}
} else {
if (ch==' ' || ch=='\r') {
trailingSpaces++;
} else if (ch=='\n') {
if (trailingSpaces>0) newCount -= trailingSpaces;
trailingSpaces=0;
isBegin=true;
} else if (trailingSpaces>0) {
trailingSpaces=0;
}
newBuf[newCount]=ch;
newCount++;
}
}
return new String(newBuf, 0, newCount-trailingSpaces);
}