How to split a string in java using stringtokenizer

Here we will learn to split the String in parts on the basis of tokens provided.

There are different way to split string.

  1. Using StringTokenizer
  2. Using Split method from String Class
  3. Scanner Class
In this article we will only discuss first way to split the string. Other two will be discussed in separate topic.
package com.jbt;

import java.util.StringTokenizer;

/*
 * Here we will learn to split a string usign string tokenizer.
 */
public class SplitStringUsingStringTokenizer {

	public static void main(String args[]) {
		String strWithSpace = "Java Beginners Tutorial";
		String strWithDelimeter = "Hello |Hi|How";

		/*
		 * Constructs a string tokenizer for the specified string. The
		 * characters in the delim argument are the delimiters for separating
		 * tokens. Delimiter characters themselves will not be treated as
		 * tokens.
		 */
		StringTokenizer strToken = new StringTokenizer(strWithDelimeter, "|");

		/*
		 * Note* Space is the default token for StringTokenizer.
		 */
		// StringTokenizer strTokenSpace = new StringTokenizer(strWithSpace, " "); this code and below code is same.
		StringTokenizer strTokenSpace = new StringTokenizer(strWithSpace);

		System.out.println("Splitting the string on the basis of | tokens");
		while (strToken.hasMoreTokens()) {

			System.out.println(strToken.nextElement());

		}

		System.out.println("Splitting the string on the basis of Spaces");
		while (strTokenSpace.hasMoreTokens()) {

			System.out.println(strTokenSpace.nextElement());

		}

	}

}

Output of the above programme will be.

Splitting the string on the basis of | tokens
Hello
Hi
How
Splitting the string on the basis of Spaces
Java
Beginners
Tutorial

 

By | 2012-09-15T02:54:36+00:00 September 15th, 2012|Code Base|0 Comments

About the Author:

Leave A Comment