Split a String on newlines in Java
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'.
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.Arrays; public class Main { public static void main(String[] args) { String str = "C++\nJava\nKotlin"; String[] lines = str.split("\r?\n|\r"); System.out.println(Arrays.asList(lines)); // [C++, Java, Kotlin] } } |
Here’s a version that skips empty lines:
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.Arrays; public class Main { public static void main(String[] args) { String str = "C++\nJava\n\nKotlin"; String[] lines = str.split("[\r\n]+"); System.out.println(Arrays.asList(lines)); // [C++, Java, Kotlin] } } |
Output:
[C++, Java, Kotlin]
A better solution is to use the linebreak matcher \R which matches with any Unicode linebreak sequence.
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.Arrays; public class Main { public static void main(String[] args) { String str = "C++\r\nJava\r\nKotlin"; String[] lines = str.split("\\R"); System.out.println(Arrays.asList(lines)); // [C++, Java, Kotlin] } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.Arrays; public class Main { public static void main(String[] args) { String str = "C++\r\nJava\r\nKotlin"; String[] lines = str.split(System.lineSeparator()); System.out.println(Arrays.asList(lines)); // [C++, Java, Kotlin] } } |
That’s all about splitting a string on newlines in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)