StringTokenizer

Tokenize String with StringTokenizer

In this example we shall show you how to tokenize a String with StringTokenizer. The StringTokenizer is used to break a String into tokens. To tokenize a String with StringTokenizer one should perform the following steps:

  • Get a new StringTokenizer for a specified String, using the StringTokenizer(String str) constructor.
  • Get the tokens of the String, using hasMoreTokens() and nextToken() API methods of StringTokenizer. Since no delimiter has been set, one of the delimiters in the default delimiter set is used, that is here the space character,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

import java.util.StringTokenizer;

public class TokenizeStringWithStringTokenizer {
	
	public static void main(String[] args) {
		
		StringTokenizer st = new StringTokenizer("Java Code Geeks - Java Examples");
		 
		// lop through tokens
		while(st.hasMoreTokens()) {
			System.out.println(st.nextToken());
		}
		
	}

}

Output:

Java
Code
Geeks
-
Java
Examples

 
This was an example of how to tokenize a String with StringTokenizer in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button