Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to split text into lines

Short answer

The lines() method returns a stream of lines and understands line breaks from every system — \n, \r\n and \r:

void main() {
    String text = "first\r\nsecond\nthird";
    List<String> lines = text.lines().toList();
 
    IO.println(lines);
    IO.println(lines.size());
}

Output:

[first, second, third]
3

Numbering lines

Once you have a list, you can walk it with an index:

void main() {
    var lines = "apple\nbanana\ncherry".lines().toList();
    for (int i = 0; i < lines.size(); i++) {
        IO.println((i + 1) + ": " + lines.get(i));
    }
}

Output:

1: apple
2: banana
3: cherry

Skipping empty lines

In a stream you can easily drop empty lines and extra spaces:

void main() {
    String text = """
            milk
 
              bread
            eggs
            """;
 
    var items = text.lines().map(String::strip).filter(line -> !line.isEmpty()).toList();
    IO.println(items);
}

Output:

[milk, bread, eggs]

With split

split("\\R") does the same but returns an array. \\R in a regular expression means any line break:

void main() {
    String[] lines = "a\r\nb\nc".split("\\R");
    IO.println(lines.length);
}

Output:

3

Common mistake

Splitting by "\n". Text from Windows files contains \r\n, and an invisible \r stays at the end of each line:

void main() {
    String[] lines = "yes\r\nno".split("\n");
 
    IO.println(lines[0].equals("yes"));
    IO.println(lines[0].length());
}

Output:

false
4

Functions used in this recipe

  • String.lines() — Splits a string at line breaks and returns the lines as a stream.
  • String.split() — Splits a string into an array of parts by a separator.
  • String.strip() — Removes any Unicode whitespace from both ends of a string.

Thanks for reading!

Donate to the site — we work hard for you.