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 
5
  • 2
    Why not use String.split()? StringTokenizer is a legacy class. Commented Feb 2, 2017 at 11:38
  • thanks a lot, I will try with String.split() Commented Feb 2, 2017 at 11:44
  • it did not solve my problem, I can only choose how many of them I want to "print out ", but I still cant choose which one. Commented Feb 2, 2017 at 11:55
  • There is no law that says you have to use a loop. You can just use several if statements one after the other to check if there is still a token and get the next token and do something with it. Commented Feb 2, 2017 at 11:56
  • thanks @RealSkeptic, Commented Feb 2, 2017 at 12:05

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.