当某些值为空时,如何从逗号分隔的值列表中提取值?

时间:2012-01-08 01:49:14

标签: java string

我正在使用的Web服务返回逗号分隔的值列表:

a,b,,d,,f,,h,,j,,l,,,

当一些容器变量为空时,如何将它们提取到各自的容器变量中?

String a = ...;
String b = ...;
String c = ...;
String d = ...;
String e = ...;
String f = ...;
String g = ...;
String h = ...;
String i = ...;
String j = ...;
String k = ...;
String l = ...;

3 个答案:

答案 0 :(得分:3)

String[] result = "a,b,,d,,f,,h,,j,,l,,,".split(",");

然后,您可以将a,b,c等分配给result

的元素
String a = result[0];
...

答案 1 :(得分:3)

String[] arr = yourString.split(",", -1);
String a = arr[0];
String b = arr[1];
...etc...

空字符串将以""的形式返回,包括最后的字符串。因此"a,b,,".split(",", -1)将生成以下数组:{ "a", "b", "", "" }

另一方面,如果它们是空的,你对尾随字符串不感兴趣,请执行以下操作:

String[] arr = yourString.split(",");

这样,将删除尾随的空字符串(如果有的话)。因此"a,b,,".split(",")会产生{ "a", "b" }

答案 2 :(得分:1)

最好使用数组而不是单个变量a,b,...。然后你可以像其他人建议的那样使用split并完成它:

String full_line = // get the full line from your web service.
String[] abc_etc = full_line.split(",");
// abc_etc now contains all fields, in order.  
// Do note that empty fields are stored as "", not null.

如果确实需要将它们存储在单个变量中,您需要一次只执行一次:

String full_line = // get the full line from your web service.
String[] fields = full_line.split(",");
String a = fields[0];
String b = fields[1];
String c = fields[2];
...

如果您想要null而不是"",请添加支票:

String a = fields[0].equals("")? null : fields[0];