我有以下字符串:
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 中的空字符串?当然,我可以编写一段多行的代码,但是在我浪费时间去实现它之前,我想知道是否有一个简单的方法或者额外的两行左右的代码可以帮助我。谢谢!