The StringTokennizer class is use to split a String object into different tokens by certain delimiter. (space is the default delimiter)

StringTokenizer example

Here’s an example to split a string by “space” and “comma” delimiter, and iterate the StringTokenizer elements and print it out one by one.

package com.mkyong.common;
 
import java.util.StringTokenizer;
 
public class App 
{
    public static void main( String[] args )
    {
 
    	String str = "This is String , split by StringTokenizer, created by mkyong";
    	StringTokenizer st = new StringTokenizer(str);
 
    	System.out.println("---- Split by space ------");
    	while(st.hasMoreElements()){
    		System.out.println(st.nextElement());
    	}
 
    	System.out.println("---- Split by comma ',' ------");
        StringTokenizer st2 = new StringTokenizer(str,",");	
 
    	while(st2.hasMoreElements()){
    		System.out.println(st2.nextElement());
    	}
    }
}

Output

---- Split by space ------
This
is
String
,
split
by
StringTokenizer,
created
by
mkyong
---- Split by comma ',' ------
This is String 
 split by StringTokenizer
 created by mkyong

Reference

http://java.sun.com/javase/6/docs/api/java/util/StringTokenizer.html

This article was posted in Java category.