【问题标题】:Easy way of getting List<String> from String by splitting on EOL?通过在 EOL 上拆分从 String 获取 List<String> 的简单方法?
【发布时间】:2015-09-05 10:39:09
【问题描述】:

如何从String 中的行中获取List&lt;String&gt;?我想将 CRLF (\r\n) 和 LF (\n) 作为 EOL 处理。需要保留包括尾随在内的空行,以便我可以使用String.join("\n", ...) 来取回原始的String(但是,我不介意CRLFs 是否变为LFs)。

这是我想出的:

String x = "\r\n\r\na\nb\r\nc\n\r\n\n";

List<String> lines = Arrays.asList(org.apache.commons.lang3.StringUtils.splitPreserveAllTokens(x.replace("\r", ""), "\n"));

我见过 various 其他 questions 但他们似乎不需要 保留空行 部分。

【问题讨论】:

  • String.split() 破坏尾随行。
  • String.split 采用正则表达式,因此您可以轻松处理CRLRLF

标签: java


【解决方案1】:

使用 StringReader 和 Stream:

    String x = "\r\n\r\na\nb\r\nc\n\r\n\n";
    List<String> list = new BufferedReader(new StringReader(x))
        .lines()
        .collect(Collectors.toList());

【讨论】:

    【解决方案2】:

    你可以试试

    String[] result = yourString.split("\r?\n", -1);
    

    -1 参数是limit,它的负值意味着不应从结果String[] 数组中删除尾随的空字符串(我假设将此数组转换为List&lt;String&gt; 对您来说不是什么大问题)。

    【讨论】:

    • 我不知道If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. 是如何翻译成它以这种方式工作的,但它确实有效! [String.split(String, int)][docs.oracle.com/javase/8/docs/api/java/lang/… 中的示例甚至有这个!
    【解决方案3】:

    如果您不想使用String.split 所需的正则表达式,您可以使用BufferedReaderreadLine 方法。其文档摘录:

    读取一行文本。行被视为由换行符 ('\n')、回车符 ('\r') 或回车符后紧跟换行符中的任何一种来终止。

    请注意,它也单独在“\r”上拆分。

    所以你基本上会做以下事情:

    String x = ...
    BufferedReader reader = new BufferedReader(new StringReader(x));
    List<String> lines = new ArrayList<>();
    String line;
    while ((line = reader.readLine()) != null) {
        lines.add(line);
    }
    

    注意,使用 Java 8 会更容易:

    String x = ...
    BufferedReader reader = new BufferedReader(new StringReader(x));
    List<String> lines = reader.lines().collect(Collectors.toList());
    

    【讨论】:

      【解决方案4】:

      试试这个:

       String[] lines = String.split("\\r\\n?\\n");
      
       LinkedList<String> list = new LinkedList<String>();
      
       for(String s : lines) {
           list.add(s);
       }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-29
        • 1970-01-01
        • 1970-01-01
        • 2020-04-29
        • 2014-08-27
        • 1970-01-01
        • 2021-06-08
        • 1970-01-01
        相关资源
        最近更新 更多