Java:String split():我希望它在末尾包含空字符串 [英] Java: String split(): I want it to include the empty strings at the end
问题描述
我有以下字符串:
String str = "\nHERE\n\nTHERE\n\nEVERYWHERE\n\n";
如果您只是打印它,它会输出这样的(当然 \ n
不会逐字打印):
If you just print this, it would output like this (Of course the \n
wouldn't be "literally" printed):
\n
HERE\n
\n
THERE\n
\n
EVERYWHERE\n
\n
\n
当我调用方法 split(\ n)
,我想获得新行( \ n
)字符之间的所有字符串,甚至是最后的空字符串。
When I call the method split("\n")
, I want to get all strings between the new line (\n
) characters even empty strings at the end.
例如,如果我今天这样做:
For example, if I do this today:
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):
I want it to print out like this (Output A):
strArray.length - 8
strArray[0] - ""
strArray[1] - "HERE"
strArray[2] - ""
strArray[3] - "THERE"
strArray[4] - ""
strArray[5] - "EVERYWHERE"
strArray[6] - ""
strArray[7] - ""
目前,它打印如下(输出B ),并且跳过任何结束的空字符串:
Currently, it prints like this (Output B), and any ending empty strings are skipped:
strArray.length - 6
strArray[0] - ""
strArray[1] - "HERE"
strArray[2] - ""
strArray[3] - "THERE"
strArray[4] - ""
strArray[5] - "EVERYWHERE"
如何进行拆分( )
方法包括输出A中的空字符串?当然,我可以编写一行多行代码,但想知道,在我浪费时间尝试实现之前,如果有一个简单的方法或额外的两行左右的代码来帮助我。谢谢!
How do I make the split()
method include the empty strings like in Output A? I, of course, could write a multi-line piece of code, but wanted to know, before I waste my time trying to implement that, if there was a simple method or an extra two or so lines of code to help me. Thanks!
推荐答案
使用 str.split(\ n,-1)
(带负限制
参数)。当 split
被赋予零或没有 limit
参数时,它会丢弃尾随空字段,并且当它被赋予正<$ c时$ c> limit 参数它将字段数限制为该数字,但否定限制意味着允许任意数量的字段而不丢弃尾随空字段。 此处并且行为来自Perl。
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.
这篇关于Java:String split():我希望它在末尾包含空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!