This post will discuss how to split a string on newlines in Java.

Windows have a different line terminator than Unix/Linux or Mac systems. The Mac uses a standalone carriage-return character (represented as \r) to mark the end of a line. Unix, on the other hand, uses a newline (line feed) character, \n. Windows uses both, a carriage-return character followed by a line feed character (\r\n) as a line terminator.

 
The Java String class has a split() method which splits the string around matches of the given regular expression. To split a string on newlines, you can use the regular expression '\r?\n|\r' which splits on all three '\r\n', '\r', and '\n'.

Download  Run Code

 
Here’s a version that skips empty lines:

Download  Run Code

Output:

[C++, Java, Kotlin]

 
A better solution is to use the linebreak matcher \R which matches with any Unicode linebreak sequence.

Download  Run Code

Output:

[C++, Java, Kotlin]

 
You can also split a string on the system-dependent line separator string. The idea is to use the System.lineSeparator() method that returns the initial value of the system property line.separator which is system dependent. This approach should be used only if your text originates from the runtime system. It might cause issues if the text is using a different line separator than current runtime environment.

Download  Run Code

That’s all about splitting a string on newlines in Java.