2

How do I get a List<String> from lines in String? I want to handle CRLF (\r\n) and LF (\n) as EOLs. Empty lines, including those trailing need to be preserved, so that I can use String.join("\n", ...) to get back the original String (however, I don't mind if CRLFs become LFs).

This is what I've come up with:

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"));

I've seen various other questions but they don't seem to require the preserve empty lines part.

Community
  • 1
  • 1
antak
  • 19,481
  • 9
  • 72
  • 80

4 Answers4

3

Use StringReader and 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

You can try with

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

-1 parameter is limit and it negative value means that trailing empty strings should not be removed from resulting String[] array (I am assuming that converting this array to List<String> is not big problem for you).

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • I don't know how `If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.` translates to it working that way but it works! The example in [String.split(String, int)][https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-int-] even had this! – antak Jun 19 '15 at 12:48
1

If you do not want to go with a regular expression that is needed by String.split, you could use the readLine method of a BufferedReader. An excerpt of its documentation:

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Note, that it also splits on "\r" alone.

So you would basically do the following:

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

Note, with Java 8 it's easier:

String x = ...
BufferedReader reader = new BufferedReader(new StringReader(x));
List<String> lines = reader.lines().collect(Collectors.toList());
Seelenvirtuose
  • 20,273
  • 6
  • 37
  • 66
0

Try this:

 String[] lines = String.split("\\r\\n?\\n");

 LinkedList<String> list = new LinkedList<String>();

 for(String s : lines) {
     list.add(s);
 }
Nico Weisenauer
  • 284
  • 1
  • 7