java 如何用空的新行拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11717667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to split string with empty new line
提问by hudi
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 ?
问题是这不起作用。当我将新行转换为字节时,我看到 "\n\n" 表示为 10 10 但我的文件中的新行表示为 10 13 10 13。那么我该如何拆分我的文件呢?
回答by xiaowl
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.
所以你需要string.split("\n\r")
在你的情况下尝试。
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.
如果要按空行拆分,请尝试\n\r\n\r
。或者您可以使用.readLine()
读取您的文件,并跳过所有空行。
Are you sure it's 10 13 10 13
? It always should be 13 10
...
你确定是10 13 10 13
?应该总是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.
而且,你不应该line.separator
过分依赖。因为如果您正在处理来自 *nix 平台的某些文件,则它是\n
,反之亦然。甚至在 Windows 上,一些编辑器也将其\n
用作换行符。所以我建议您使用一些高级方法或使用string.replaceAll("\r\n", "\n")
来规范您的输入。
回答by Sivaa
Try using:
尝试使用:
text.split("\n\r");
回答by hovanessyan
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'snewLine() method, that takes care of that automatically.
获取行分隔符,如果你想让它独立于平台。您还可以使用BufferedWriter 的newLine() 方法,它会自动处理。
回答by Mohammod Hossain
LF: Line Feed, U+000A
CR: Carriage Return, U+000D
so you need to try to use
"string".split("\r\n");
回答by Strelok
Why are you splitting on \n\n
?
你为什么要分手\n\n
?
You should be splitting on \r\n
because that's what the file lines are separated by.
您应该拆分,\r\n
因为这是文件行的分隔符。
回答by Byter
One Solution is to Split using "\n" and neglect empty Strings
一种解决方案是使用 "\n" 拆分并忽略空字符串
List<String> lines = text.split("\n");
for(String line : lines) {
line = line.trim();
if(line != "") {
System.out.println(line);
}
}
回答by Eng.Fouad
Try to use regular expressions, something like:
尝试使用正则表达式,例如:
text.split("\W+");
text.split("\W+");
text.split("\s+");