How can we use the StringTokenizer class in Java?


A StringTokenizer is a subclass of Object class and it can allow an application to break a string into tokens. A set of delimiters can be specified either at creation time or on a per-token basis. An instance of StringTokenizer behaves in two ways depending on whether it was created with the returnDelims flag having the value true or false.

The object of StringTokenizer internally maintains a current position within the string to be tokenized. The important methods of StringTokenizer c;ass are hasMoreElements(), hasMoreTokens(), nextElement(), nextToken() and countTokens().

Syntax

public class StringTokenizer extends Object implements Enumeration<Object>

Example 1

import java.util.*;
public class StringTokenizerTest1 {
   public static void main(String args[]) {
      StringTokenizer tokens = new StringTokenizer("Welcome To Tutorials Point");
      System.out.println("countTokens : " + tokens.countTokens());
      while(tokens.hasMoreTokens()) {
         System.out.println(tokens.nextToken());
      }
   }
}

Output

countTokens : 4
Welcome
To
Tutorials
Point

Example 2

import java.util.*;
public class StringTokenizerTest1 {
   public static void main(String args[]) {
      StringTokenizer tokens = new StringTokenizer("Welcome-To-Tutorials;Point-India;Hyderabad");
      System.out.println("countTokens : " + tokens.countTokens());
      while(tokens.hasMoreTokens()) {
         System.out.println(tokens.nextToken(";"));
      }
   }
}

Output

countTokens : 1
Welcome-To-Tutorials
Point-India
Hyderabad

Updated on: 01-Dec-2023

115 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements