String split() : 我希望它在结尾包含空字符串

我有以下字符串:

String str = "\nHERE\n\nTHERE\n\nEVERYWHERE\n\n";

如果你只是打印这个,它会像这样输出(当然 \n不会“字面上”打印) :

\n
HERE\n
\n
THERE\n
\n
EVERYWHERE\n
\n
\n

当我调用方法 split("\n")时,我希望得到新行(\n)字符之间的所有字符串,甚至最后的空字符串。

例如,如果我今天这样做:

String strArray[] = str.split("\n");


System.out.println("strArray.length - " + strArray.length);
for(int i = 0; i < strArray.length; i++)
System.out.println("strArray[" + i + "] - \"" + strArray[i] + "\"");

我希望它像这样打印出来(输出 A) :

strArray.length - 8
strArray[0] - ""
strArray[1] - "HERE"
strArray[2] - ""
strArray[3] - "THERE"
strArray[4] - ""
strArray[5] - "EVERYWHERE"
strArray[6] - ""
strArray[7] - ""

当前,它像这样打印(输出 B) ,并跳过任何结束的空字符串:

strArray.length - 6
strArray[0] - ""
strArray[1] - "HERE"
strArray[2] - ""
strArray[3] - "THERE"
strArray[4] - ""
strArray[5] - "EVERYWHERE"

如何使 split()方法包括输出 A 中的空字符串?当然,我可以编写一段多行的代码,但是在我浪费时间去实现它之前,我想知道是否有一个简单的方法或者额外的两行左右的代码可以帮助我。谢谢!

50081 次浏览

The one-argument split method is specified to ignore trailing empty string splits but the version that takes a "limit" argument preserves them, so one option would be to use that version with a large limit.

String strArray[] = str.split("\n", Integer.MAX_VALUE);

use str.split("\n", -1) (with a negative limit argument). When split is given zero or no limit argument it discards trailing empty fields, and when it's given a positive limit argument it limits the number of fields to that number, but a negative limit means to allow any number of fields and not discard trailing empty fields. This is documented here and the behavior is taken from Perl.

Personally, I like the Guava utility for splitting:

System.out.println(Iterables.toString(
Splitter.on('\n').split(input)));

Then if you want to configure empty string behaviour, you can do so:

System.out.println(Iterables.toString(
Splitter.on('\n').omitEmptyStrings().split(input)));