Sunday, March 4, 2012

How do I use StringTokenizer to split a string in android?


The code below is an example of using StringTokenizer to split a string. In the current JDK this class is discouraged to be used, use the String.split(...) method instead or using the newjava.util.regex package.

import java.util.StringTokenizer;

public class StringTokenizerSample {
    public static void main(String[] args) {
        StringTokenizer st =
                new StringTokenizer("A StringTokenizer sample");

        //
        // get how many tokens inside st object
        //
        System.out.println("Tokens count: " + st.countTokens());

        //
        // iterate st object to get more tokens from it
        //
        while (st.hasMoreElements()) {
            String token = st.nextElement().toString();
            System.out.println("Token = " + token);
        }

        //
        // split a date string using a forward slash as
        // delimiter
        //
        st = new StringTokenizer("2005/12/15", "/");
        while (st.hasMoreElements()) {
            String token = st.nextToken();
            System.out.println("Token = " + token);
        }
    }
}

Below is the output....
Tokens count: 3
Token = A
Token = StringTokenizer
Token = sample
Token = 2005
Token = 12
Token = 15

No comments:

Post a Comment