[英]Java String Wrapping:How do I wrap words in a String at New line character(\n)
我們想將單詞包裝在換行符(\\ n)的字符串中。基本上,我們按ENTER鍵開始換行。
按下Enter鍵即可在“我們的消息”中創建新行。
輸入數據 :
在注釋列中捕獲了字符串。 給出的評論欄為:
EDI ORDER-SAVE COMMENTS\nC3 Generic\nLOC 0833\nExpected arrival 01/07/2016\nOTYPE NE\nTRKPC 01 GM/00007643020008361321
我們嘗試過:
string s = "EDIORDER-SAVE COMMENTS C3 Generic LOC 0833 Expected arrival 01/07/2016 OTYPE NE TRKPC 01 GM/00007643020008361321" ;
StringBuilder sb = new StringBuilder(s);
int i = 0;
while ((i = sb.indexOf(" ", i + 20)) != -1) {
sb.replace(i, i + 1, "\n");
}
轉換后的預期數據:換行符是換行符
Long String of Comment field should Splits in 6 different lines
EDI ORDER-SAVE COMMENTS
C3 Generic
LOC 0833
Expected arrival 01/07/2016
OTYPE NE
TRKPC 01 GM/00007643020008361321
輸出后的確切數據如下所示:
SalesOrder NComment SalesOrderLine StockCode
183590 EDI ORDER-SAVE COMMENTS 1
183590 2 abc-defg-13OZ-24
183590 C3 Generic 37
183590 LOC 0833 38
183590 Expected arrival 01/07/2016 39
183590 OTYPE NE 40
183590 TRKPC 01 GM/00007643020008361321 51
任何幫助,將不勝感激!
抱歉,我還沒有真正想要實現的目標。 您要在通過第20個字符的單詞之前插入中斷嗎?
StringBuilder sb = new StringBuilder(s);
int currentSpaceFound = sb.indexOf(" ");
int i = 1;
while (currentSpaceFound != -1) {
int lastOccurence = currentSpaceFound;
currentSpaceFound = sb.indexOf(" ", currentSpaceFound + 1);
if (currentSpaceFound > (20 * i)) {
sb.setCharAt(lastOccurence, '\n');
i++;
}
}
System.out.println(sb);
我認為這樣的事情應該起作用:
private String wrapComment(String comment, int length) {
if(comment.length() <= length) return comment;
StringBuilder stringBuilder = new StringBuilder(comment);
int spaceIndex = -1;
for(int i = 0; i < comment.length(); i ++) {
if(i % length == 0 && spaceIndex > -1) {
stringBuilder.replace(spaceIndex, spaceIndex+1, "\n");
spaceIndex = -1;
}
if(comment.charAt(i) == ' ') {
spaceIndex = i;
}
stringBuilder.append(comment.charAt(i));
}
return stringBuilder.toString();
}
測試:
String comment = "EDI ORDER-SAVE COMMENTS C3 Generic LOC 0833 Expected arrival 01/07/2016 OTYPE NE TRKPC 01 GM/00007643020008361321";
System.out.println(wrapComment(comment, 30));
輸出:
EDI ORDER-SAVE COMMENTS C3
Generic LOC 0833 Expected
arrival 01/07/2016 OTYPE NE TRKPC
01 GM/00007643020008361321
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.