[英]Tokenizer java (string)
For example, I ve got Some string
abcd`, I have separated it by tokens. 例如,我
ve got Some string
abcd`,我用标记将其分隔开了。 but now I want to do a specific thing with a, then something else with b, and something else with c. 但是现在我想用a做特定的事情,然后用b做其他事情,再用c做其他事情。 How can I do that?
我怎样才能做到这一点?
String value="a.b.c.d";
StringTokenizer tokenize = new StringTokenizer(value, ".");
while(tokenize.hasMoreTokens()){
String separated1= tokenize.?????;
String separated2= tokenize.?????;
String Val1 = someMethod1(separated1);
String Val2 = someMethod2(separated2);
}
//tokenize next line is not solution
Just to spell out what @RealSkeptic already said, avoid the loop: 只是为了阐明@RealSkeptic已经说过的内容,请避免循环:
String value = "a.b.c.d";
String[] separated = value.split("\\.");
if (separated.length >= 2) {
String val1 = someMethod1(separated[0]);
String val2 = someMethod2(separated[1]);
} else {
// other processing here
}
You could do something similar with a StringTokenizer
if you liked, only you would need at least two if statements to check whether there were enough tokens. 如果愿意,可以使用
StringTokenizer
类似的操作,仅需要至少两个if语句来检查是否有足够的令牌。 But as @user3437460 said, StringTokenizer
is now legacy; 但是正如@ user3437460所说,
StringTokenizer
现在是旧的; String.split()
is recommended in new code. 建议在新代码中使用
String.split()
。
Using String.split you can split about the .
使用String.split可以拆分
.
into an array. 排列成一个数组。
How about something like this which will print each token: 这样会打印每个令牌的东西怎么样:
String value = "a.b.c.d";
String[] tokens = value.split("\\.");
for (String token : tokens) {
System.out.println(token);
}
The .
的
.
needs to be escaped as the split
function takes a regexp and .
需要转义,因为
split
函数需要一个regexp和.
is a wildcard 是通配符
Why don't use split ? 为什么不使用split? Easier to use and makes more sense here
易于使用,在这里更有意义
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.