How to split a string by new line character in Java

Contents

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()

String.split(String regex)

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. 

public class SplitMethodExample
{
	public static void main (String[] args)
	{
        String input="FirstLine \nSecondLine \nThirdLine";
        String[] output = input.split("\\r?\\n");
        for (String eachline : output){
            System.out.println(eachline);
        }
	}
}

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:

FirstLine 
SecondLine 
ThirdLine

Recommended Articles