Ly Double II Ly Double II - 3 years ago 116
Java Question

Split String and keep null value

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"]


But if I have a string like this:

String y = "x,";
String result[]=y.split(",");
//i will get something thing like this:
//result[] = ["x"]


I want the keep the null value as well. Is it possible for me to get a result like this:
result[]=["x",""]
using the
split
method?

ajb ajb
Answer Source

The answer is in the javadoc for the two-argument split:

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 split says:

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download