The java.util package has StringTokenizer class that would enable us to split/tokenize a given string with a specified delimiter. By default the StringTokenizer class delimiters are the space character, the tab character, the carriage return character and the form-feed character. By default it means we have not specified the delimiter in the StringTokenizer constructor. In our given example we wan to parse 01-02-03-04656-TEST. Base on the input string the delimiter is the dash character “-“. Here is a sample source code that would parse a given string into tokens.

package com.javatutorialhq.tutorial;

import java.util.StringTokenizer;

public class SplitUsingTokenizer {

	/**
	 * This java sample code shows how to split
	 * String value into tokens using
	 * StringTokenize. This program tokenize
	 * the input string base on the delimiter
	 * set in the constructor of the StringTokenizer
	 * class.
	 */
	public static void main(String[] args) {
		String input = "01-02-03-04656-TEST";
		StringTokenizer st = new StringTokenizer(input,"-");
		while(st.hasMoreTokens()){
			System.out.println(st.nextToken());
		}
	}
}

Running the code above would give you the following output:

01
02
03
04656
TEST

The StringTokenizer constructor that we invoke is of this format StringTokenizer(String input, String delimiter). Thus instead of using the default delimiter as specified on the first paragraph, our tokenizer used the dash “-” character as delimiter.

Suggested Reading List