StringTokenizer in Java

StringTokenizer in Java

String tokenizer class is useful to break string into tokens(pieces). These tokens are then stored in the StringTokenizer object from where they can be retrieved. The code to create an object to StringTokenizer class is :

StringTokenizer st = new StringTokenizer(string, "delimeter");

In the preceding statement, the actual string is broken into pieces at the position marked by a group of characters called ‘delimeter’. For example, to break the String wherever a comma is found we can write –

StringTokenizer st = new StringTokenizer(string, ",");

Similarly, to break the String based on comma/colon (,/:) or both, we can use –

StringTokenizer st = new StringTokenizer(string, ",:");

StringTokenizer Class Methods

  • int countTokens() : This method counts and returns the number of tokens available in a StringTokenizer object.
  • boolean hasMoreTokens(): This method tests if there are more tokens available in the StringTokenizer object or not. If next token is there then it returns true.
  • String nextToken(): This method returns the next token from the StringTokenizer.

Example to demonstrate splitting of string using StringTokenizer class :-

package com.c2s.collection;

import java.util.StringTokenizer;

public class StringTokenizerDemo {

	public static void main(String[] args) {
		String str1 = "India is a great country";
		String str2 = "This is,a test:string to show,StringTokenizer:demo";
		
		StringTokenizer st1 = new StringTokenizer(str1," "); // based on space
		StringTokenizer st2 = new StringTokenizer(str2,",:"); // based on comma & colon
		
		System.out.println("String 1 -'"+str1+"' and Tokens are :-");
		while(st1.hasMoreTokens()){
			String strToken1 = st1.nextToken();
			System.out.println(strToken1);
		}
		
		System.out.println("String 2 -'"+str2+"' and Tokens are :-");
		while(st2.hasMoreTokens()){
			String strToken2 = st2.nextToken();
			System.out.println(strToken2);
		}

	}

}

Output:

String 1 -'India is a great country' and Tokens are :-
India
is
a
great
country
String 2 -'This is,a test:string to show,StringTokenizer:demo' and Tokens are :-
This is
a test
string to show
StringTokenizer
demo

Stay tuned for more updates !

Leave a Reply

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