2

For example, Ive got Some stringa.b.c.d`, I have separated it by tokens. but now I want to do a specific thing with a, then something else with b, and something else with 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 
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
mica1234
  • 27
  • 5

3 Answers3

3

Just to spell out what @RealSkeptic already said, avoid the loop:

    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. But as @user3437460 said, StringTokenizer is now legacy; String.split() is recommended in new code.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
1

Using String.split you can split about the . 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 . is a wildcard

Will
  • 6,561
  • 3
  • 30
  • 41
0

Why don't use split ? Easier to use and makes more sense here

Sylvain Attoumani
  • 1,213
  • 1
  • 15
  • 34