开发者

split method of String class does not include trailing empty strings [duplicate]

This question already has answers here:开发者_如何学Go Closed 10 years ago.

Possible Duplicate:

Java split() method strips empty strings at the end?

The split method of String class does not include trailing empty strings in the array it returns. How do I get past this restriction:

class TestRegex{
 public static void main(String...args){
  String s = "a:b:c:";    
  String [] pieces = s.split(":");

  System.out.println(pieces.length); // prints 3...I want 4.
 }
}


According to the documentation:

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero.

For the split with the limit argument, it says:

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

So, try to call the split method with a non-positive limit argument, like this:

String[] pieces = s.split(":", -1);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜