Languages
[Edit]
EN

Java - how to split string by new line character?

6 points
Created by:
JustMike
26120

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

 

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join