我有以下代碼: String s = "A very long string containing " + "many many words and characters. " + "Newlines will be entered at spaces."; StringBuilder sb = new StringBuilder(s); int i = 0; while ((i = sb.indexOf(" ", i + 20)) != -1) { sb.replace(i, i + 1, "\n"); } System.out.println(sb.toString());代碼的輸出為:A very long string containingmany many words andcharacters. Newlineswill be entered at spaces.上面的代碼將字符串包裝在每30個字符的下一個空格之后,但是我需要將字符串包裝在每30個字符的前一個空格之后,就像第一行一樣:A very long string第二行是containing many請給出一些適當的解決方案。
3 回答

泛舟湖上清波郎朗
TA貢獻1818條經驗 獲得超3個贊
您可以嘗試以下方法:
public static String wrapString(String s, String deliminator, int length) {
String result = "";
int lastdelimPos = 0;
for (String token : s.split(" ", -1)) {
if (result.length() - lastdelimPos + token.length() > length) {
result = result + deliminator + token;
lastdelimPos = result.length() + 1;
}
else {
result += (result.isEmpty() ? "" : " ") + token;
}
}
return result;
}
調用為wrapString(“ asd xyz afz”,“ \ n”,5)
添加回答
舉報
0/150
提交
取消