I want the split a string but also keep the null value. For example, I have a string like this:
String x = "x,y";
String result = y.split(",");
// then i will get result like this:
//result = ["x","y"]
String y = "x,";
//i will get something thing like this:
//result = ["x"]
The answer is in the javadoc for the two-argument
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. 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.
The javadoc for the one-argument
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
The last two sentences of the 2-argument javadoc imply that negative values of
limit have the same behavior as a zero value (which is the same behavior as the one-argument
split) except for the trailing empty strings. So if you want to keep the trailing empty strings, any negative value for the limit will work. Thus:
String result = y.split(",", -1);