[英]validate null string while using tokenizer
I have a String like this: String sample = "a|b||d|e";
我有一个像这样的字符串:
String sample = "a|b||d|e";
and I'm trying to split the string with tokenizer 我正在尝试用tokenizer分割字符串
StringTokenizer tokenizer = new StringTokenizer(sample, "|");
String a = tokenizer.nextToken();
String b = tokenizer.nextToken();
String c = tokenizer.nextToken();
String d = tokenizer.nextToken();
When I use the above code, the String variable c
is assigned to the value d
. 当我使用上面的代码时,字符串变量
c
被分配给值d
。
StringTokenizer
doesn't initialize a null
value to String c
. StringTokenizer
不会将null
初始化为String c
。
How can we validate and assign default value like -
if it is null
? 我们如何验证和分配默认值,例如
-
如果它为null
?
As others have said, you can use String#split()
on pipe, which would return an entry for the empty match. 正如其他人所说,您可以在管道上使用
String#split()
,这将返回空匹配项。 In the code snippet below, I use streams to map the empty entry into dash per your desired output. 在下面的代码片段中,我使用流将空条目映射到每个所需输出的破折号中。
String sample = "a|b||d|e";
String[] parts = sample.split("\\|");
List<String> list = Arrays.asList(parts).stream()
.map(o -> {
if (o.equals("")) {
return "-";
} else {
return o;
}
}).collect(Collectors.toList());
for (String part : list) {
System.out.println(part);
}
Output: 输出:
a
b
-
d
e
Demo here: 演示在这里:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.