split method of String class does not include trailing empty strings [duplicate]
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);
精彩评论