String's split method does not include trailing blank lines

Possible duplicate:
Java split () method breaks blank lines at end?

The String class splitting method does not include terminating empty strings in the returned array. How to overcome this limitation:

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. } } 
+6
java regex
source share
1 answer

According to the documentation :

This method works as if a separation method with two arguments with a given expression and a limit argument of zero.

To split up with a marginal argument, he says:

If n is not positive, then the pattern will be applied as many times as possible, and the array can be of any length. If n is zero, then the template will be applied as many times as possible, the array can be of any length and the final empty lines will be discarded.

So, try calling the split method with a non-positive limit argument, for example:

 String[] pieces = s.split(":", -1); 
+16
source share

All Articles