java - 分割字符串并保留空值

标签 java string split

我想要分割一个字符串,但也保留空值。例如,我有一个这样的字符串:

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/

相关文章:

java - Spring:模拟 beans 的正确方法

Java quote.split 为仅 1 个单词

java - 在 Coldfusion/Java 中拆分多语言字符串

javascript - 拆分键值对,给它们新的键

java - Sqoop 尝试连接 Mysql 时出错

java - 如何在使用 JPA 和 Hibernate 获得 OptimisticLockException 时重试服务方法

c - 拼写检查算法

c# - 是否有一行代码可以获取该字符串的特定部分?

c++ - 初始化临时字符串以保持条件可读是否可以接受?

sql - 将两个相互依赖的字符串拆分为行