[英]how to use java stringtokenizer?
how to use java stringtokenizer for the below string 如何为以下字符串使用java stringtokenizer
|feild1|field2||field4|... | feild1 | field2 || field4 | ...
i want java to take the blank as a field too, but stringtokenizer is skipping it. 我也想让java也将空白作为字段,但是stringtokenizer跳过了它。
Any option to get it?. 有任何选择吗?
What about java.util.Scanner ? 那java.util.Scanner呢? Much more powerful than the StringTokenizer, introduced in Java 5 and mostly unknown or underrated:
比Java 5中引入的StringTokenizer强大得多,并且大多数未知或被低估了:
Scanner scanner = new Scanner("1|2|3|||6|");
scanner.useDelimiter("\\|");
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
EDIT: It can even parse the ints (and other types) directly, like this: 编辑:它甚至可以直接解析ints(和其他类型),如下所示:
Scanner scanner = new Scanner("1|2|3|||6|");
scanner.useDelimiter("\\|");
while (scanner.hasNextInt()) {
int x = scanner.nextInt();
System.out.println(x);
}
Do you really need a Tokenizer? 您真的需要令牌生成器吗? Why not split the string to an array?
为什么不将字符串拆分为数组? This way you will have the empty fields too.
这样,您也将有空字段。
String fields = "bla1|bla2||bla3|bla4|||bla5";
String[] field = fields.split("\\|"); // escape the | because split() needs a regexp
Without StringTokenizer using String.split() : 没有使用String.split()的 StringTokenizer:
for (String a : "|1|2||3|".split("\\|")) {
System.out.println("t="+a);
}
Update: forgot the escaping (as usual). 更新:忘记转义(如往常一样)。 +1 vote.
+1票。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.