Using the StringTokenizer to Split a String


This example shows how to split a string using the StringTokenizer class.
The StringTokenizer has three contructors and one of them takes the String to be split as parameter, and that is the constructor we use in this example.
Since no delimiter is passed to it the default delimiters for the StringTokenizer are used:

- the space character
- the tab character
- the newline character
- the carriage-return character
- and the form-feed character

In this example we only use the space character.
After the StringTokenizer object is constructed it is possible to check how many tokens it contains by using the countTokens() method.

Do display each token we iterate through it using the hasMoreElements() method and call nextToken().
In order to use the hasMoreElements() method the StringTokenizer must implement the Iterator interface which also contains a method called nextElement().
We could as easily use that method (which is commented out below). The only difference is that it returns an Object instance as opposed to the nextToken() method which returns a String object.


package com.javadb.examples;

import java.util.StringTokenizer;

/**
 *
 * @author www.javadb.com
 */

public class Main {

    public static void main(String[] args) {
        StringTokenizer tokenizer =
                new StringTokenizer("This is a StringTokenizer Java Code Example");

        //Check the number of tokens that this tokenizer object contain
        System.out.println("Number of tokens: " + tokenizer.countTokens());

        //Iterate through the tokenizer object and print out each element
        while (tokenizer.hasMoreElements()) {
            String token = tokenizer.nextToken();
            System.out.println(token);
        }

        //Using the nextElement method:
        /*
        while (tokenizer.hasMoreElements()) {
            String token = tokenizer.nextElement().toString();
            System.out.println("token1 = " + token);
        }
        */

    }
}

The output from the code above would be:

This
is
a
StringTokenizer
Java
Code
Example

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: