Languages
[Edit]
EN

Java - split string by new line character

6 points
Created by:
Inferio
328

1. Overview

String example = "...";

// split string by new line - \n
String[] split1 = example.split("\n");

// split string by regex - \\r?\\n
// \\r? - this is optional
// so this regex will support most important platforms:
// - Windows - \r\n
// - UNIX / Linux / MacOS - \n
String[] split2 = example.split("\\r?\\n");

2. Java split string by new line - \n

Code example: 

public class JavaSplitStringByNewLineExample1 {

    public static void main(String[] args) {

        String example =
                "How\n" +
                "to\n" +
                "split\n" +
                "\n" +
                "\n" +
                "string\n";

        String[] split = example.split("\n");
        System.out.println("# Original string: ");
        System.out.println(example);
        System.out.println();

        System.out.println("# Split by new line character: ");
        int cnt = 1;
        for (String str : split) {
            System.out.println(cnt + " - " + str);
            cnt++;
        }
    }
}

Output:

# Original string:
How
to
split


string


# Split by new line character:
1 - How
2 - to
3 - split
4 -
5 -
6 - string

3. Java split string by regex - \\r?\\n - support for most important platforms Windows, Unix, Linux MacOS

Code example with explanation in comment:

public class JavaSplitStringByNewLineExample2 {

    public static void main(String[] args) {

        String example =
                "How\n" +
                "to\r\n" +
                "split\r\n" +
                "\n" +
                "\r\n" +
                "string\n";

        // \\r?\\n
        // \\r? - this is optional
        // so this regex will support: 
        // - Windows - \r\n
        // - UNIX / Linux / MacOS - \n 
        String[] split = example.split("\\r?\\n");
        System.out.println("# Original string: ");
        System.out.println(example);
        System.out.println();

        System.out.println("# Split by new line character: ");
        int cnt = 1;
        for (String str : split) {
            System.out.println(cnt + " - " + str);
            cnt++;
        }
    }
}

Output:

# Original string:
How
to
split


string


# Split by new line character:
1 - How
2 - to
3 - split
4 -
5 -
6 - string

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - String (popular problems)

Java - how to split string by new line character?
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join