How to split a string by new line character in Java

String.split( ) in Java

The string split() method breaks a given string around matches of the given regular expression. This method takes a regular expression as parameter, and breaks the given string around matches of this regex.

Syntax of String.split()

regex − the delimiting regular expression. Based on this regex string,the input string will get splitted in this method.

Example to split a string by new line character

In the below program ,the new line character(“\n) is given in the split method.

In Unix/Linux, lines are separated by the character “\n”. In Windows,the separator is “\r\n”. To combine the logic for both scenario, the correct regular expression to denote line feeds for both platform is “\r?\n”. This means that “\r” is optional while “\n” is required. 

Since backslash(“\'”) is a special character in Java,We need to add double backslash(“\\n”) for the new line character to escape “\” in regular expression.

Output:

Recommended Articles