Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

Java - how to split string by new line character?

0 contributions
6 points

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

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more