how to use java stringtokenizer?
how to use java stringtokenizer for the below string
|feild1|field2||field4|...
i want java to take the blank as a field too, but stringtokenizer is skipping it.
Any op开发者_开发问答tion to get it?.
What about java.util.Scanner? Much more powerful than the StringTokenizer, introduced in Java 5 and mostly unknown or underrated:
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:
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():
for (String a : "|1|2||3|".split("\\|")) {
System.out.println("t="+a);
}
Update: forgot the escaping (as usual). +1 vote.
精彩评论