Java – How to Split String by New Line

In Java, we can use regex \\r?\\n to split a String by new line.

Different operating system has a different new line

  • UNIX or Mac \r
  • Windows \r\n
SplitByNewLineExample.java

package com.mkyong;

public class SplitByNewLineExample {

    public static void main(String[] args) {

        StringBuilder sb = new StringBuilder("");
        sb.append("aaa \n");
        sb.append("bbb   \r\n");
        sb.append("ccc\n");
        sb.append("\n");
        sb.append("ddd\r\n");
        sb.append("\r\n");
        sb.append("eee\n");

        String text = sb.toString();
        System.out.println("---Original---");
        System.out.println(text);

        System.out.println("---Split---");
        int count = 1;

        // split by new line
        String[] lines = text.split("\\r?\\n");
        for (String line : lines) {
            System.out.println("line " + count++ + " : " + line);
        }
    }

}

Output


---Original---
aaa 
bbb   
ccc

ddd

eee

---Split---
line 1 : aaa 
line 2 : bbb   
line 3 : ccc
line 4 : 
line 5 : ddd
line 6 : 
line 7 : eee

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
yuriNeel Recent comment authors
newest oldest most voted
yuri
Guest
yuri

Thanks!.
(“\r?\n”); helped a lot!

Neel
Guest
Neel

Hi mkyong,

Thanks for sharing the details, I took help from this article in my development project.

Thanks