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

 

1 Comment How to split a string in java using stringtokenizer

  1. priya

    Tokens are the various Java program elements which are identified by the compiler. A token is the smallest element of a program that is meaningful to the compiler.

    Reply

Leave A Comment

Your email address will not be published. Required fields are marked *

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