tags:

views:

234

answers:

3

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 option to get it?.

+8  A: 

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
Note that this will ignore trailing blank fields (i.e. "bla5||" returns `new String[] {"bla5"}`
Aaron Digulla
Thanx it worked.:)
someguy
@Aaron Digulla: this can be fixed. Use .split("\\|", -1) to get trailing blank fields
Tim Büthe
+3  A: 

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.

dz
You will need to escape the `|`.
Bart Kiers
+11  A: 

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);
}
Tim Büthe
Now this is cool here.
Winston Chen
Definitely unknown to me and underrated. Thanks.
pimpf0r