Reputation: 399
We want to wrap the word in a string at New Line character(\n).Basically, We are pressing ENTER to start a new line.
that is Enter key to create a new line in Our message when pressed.
Input data :
String is captured in comment column. Comment column given is:
EDI ORDER-SAVE COMMENTS\nC3 Generic\nLOC 0833\nExpected arrival 01/07/2016\nOTYPE NE\nTRKPC 01 GM/00007643020008361321
We tried on it:
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");
}
Expected data after transformation: linebreak is new line character
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
Exact data after output look like :
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
Any help on it would be much appreciated !
Upvotes: 0
Views: 2406
Reputation: 2759
I think something like this should work:
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();
}
Testing:
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));
Output:
EDI ORDER-SAVE COMMENTS C3
Generic LOC 0833 Expected
arrival 01/07/2016 OTYPE NE TRKPC
01 GM/00007643020008361321
Upvotes: 1
Reputation: 572
Sorry, I don't really get what you want to achieve. Do you want to insert the break BEFORE the word which passes the 20th character?
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);
Upvotes: 1