Split String By Line in Java

Split String By Line in Java | Sometimes string may contain multiple paragraphs separated by lines, and we need to split them based on the line. Here we will discuss how to split a string by a new line in Java.

To split strings in Java we can take the help of the split() method. The split() method given in the Java String class is used to divide the string into an array of strings based on some regular expression. To split a string based on the line we can use the ā€˜\nā€™ character which represents a line.

Program to Split String By Line in Java

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String string = "Hi.\nHow are you?\nAre you eating?";
        String[] lines = string.split("\n");
        System.out.println(Arrays.toString(lines));
    }
}

Output:-

[Hi., How are you?, Are you eating?]

We have taken a string that contains multiple lines and we want to split it based on the lines. For this, we have called the String class split() method by passing ā€˜\nā€™ as a regular expression. The resultant strings are stored in the array of strings.

To display an array of strings we have used the toString() method of the Java Arrays class. It converts an array to a string. But if we want to display elements separately then we can take the help of for or for-each loop.

public class Main {
    public static void main(String[] args) {
        String string = "Hi.\nHow are you?\nAre you eating?";
        String[] lines = string.split("\n");
        for (String line : lines) {
            System.out.println(line);
        }
    }
}

Output:-

Hi.
How are you?
Are you eating?

Let us see another program to split string by new line in Java.

public class Main {
    public static void main(String[] args) {
        String string = "Hello\nWorld\nJava";
        String[] lines = string.split("\n");
        for (String line : lines) {
            System.out.println(line);
        }
    }
}

Output:-

Hello
World
Java

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.