简体   繁体   中英

How to split string with empty new line

my file contains this string:

a

b

c

now I want to read it and split it with empty line so I have this:

text.split("\n\n"); where text is output of file

problem is that this doesnt work. When I convert new line to byte I see that "\\n\\n" is represented as 10 10 but new line in my file is represented by 10 13 10 13. So how I can split my file ?

Escape  Description            ASCII-Value
\n      New Line Feed (LF)     10
\r      Carriage Return (CR)   13

So you need to try string.split("\\n\\r") in your case.

Edit

If you want to split by empty line , try \\n\\r\\n\\r . Or you can use .readLine() to read your file, and skip all empty lines.

Are you sure it's 10 13 10 13 ? It always should be 13 10 ...

And, you should not depend on line.separator too much. Because if you are processing some files from *nix platform, it's \\n , vice versa. And even on Windows, some editors use \\n as the new line character. So I suggest you to use some high level methods or use string.replaceAll("\\r\\n", "\\n") to normalize your input.

尝试使用:

text.split("\n\r");

Keep in mind, sometimes you have to use:

System.getProperty("line.separator");

to get the line separator, if you want to make it platform independent. You can also use BufferedWriter's newLine() method, that takes care of that automatically.

Why are you splitting on \\n\\n ?

You should be splitting on \\r\\n because that's what the file lines are separated by.

One Solution is to Split using "\\n" and neglect empty Strings

List<String> lines = text.split("\n");

for(String line : lines) {
  line = line.trim();
  if(line != "") {
      System.out.println(line);
  }
}

尝试使用正则表达式,例如:

 
 
 
 
  
  
  text.split("\\\\W+");
 
 
  

text.split("\\s+");
LF: Line Feed, U+000A
CR: Carriage Return, U+000D

so you need to try to use  
"string".split("\r\n");

使用扫描仪对象,而不用担心字符/字节。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM