Java How to Split String by New Line

摘要: In Java, we can use regex \\r?\\n to split a 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

上一篇: Oracle PL/SQL – Before DELETE Trigger example
下一篇: PDFBox How to read PDF file in Java
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号