我们想用新行字符(\ 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
非常感谢任何帮助!
答案 0 :(得分:1)
对不起,我没有真正得到你想要达到的目标。你想在传递第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);
答案 1 :(得分:1)
我认为这样的事情应该有效:
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