我想要分割一个字符串,但也保留空值。例如,我有一个这样的字符串:
String x = "x,y";
String result[] = y.split(",");
// then i will get result like this:
//result[] = ["x","y"]
但是如果我有一个像这样的字符串:
String y = "x,";
String result[]=y.split(",");
//i will get something thing like this:
//result[] = ["x"]
我也希望保留空值。我是否有可能得到这样的结果:result[]=["x",""]
使用split
方法?
最佳答案
答案就在 javadoc对于两个参数分割
:
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.
javadoc对于单参数 split
说:
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.
2 参数 javadoc 的最后两句话暗示 limit
的负值与零值具有相同的行为(这与单参数 split
) 除了尾随的空字符串。因此,如果您想保留尾随的空字符串,则限制的任何负值都可以。因此:
String result[] = y.split(",", -1);
关于java - 分割字符串并保留空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45273764/