我们想要将单词包装在字符串中的换行符 (\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");
}
转换后的预期数据: linebreak 是换行符
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);
关于Java 字符串换行 :How do I wrap words in a String at New line character(\n),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38146044/