Java 字符串换行 :How do I wrap words in a String at New line character(\n)

标签 java regex string conditional-statements newline

我们想要将单词包装在字符串中的换行符 (\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/

相关文章:

java - 如何将圆圈移动到 "WEST"边框布局框?

java - 对 Jtable 中的行进行排序时出错

java - Cassandra 的指标监控 native API

java - 使用 Java/regex 从字符串中提取数据

sql - 使用 Oracle INSTR 函数搜索多个字符串

C# 存储输入文件中的字符串以供操作和使用的最佳方式?

regex - 我们如何匹配任何单个字符,包括 Perl 正则表达式中的换行符?

php - 自由的货币正则表达式

c++ - C++ 中用于并行化的字符串数组

c++ - 将 std::string 转换为 v8::string,反之亦然?