Program to demonstrate the use of "StringTokenizer" class

The StringTokenizer class allows an application to break a string into tokens. The StringTokenizer methods do not distinguish among identifiers, numbers, and quoted strings, nor do they recognize and skip comments. A StringTokenizer object internally maintains a current position within the string to be tokenized.
A token is returned by taking a substring of the string that was used to create the StringTokenizer object. The following example demonstrate the use of the tokenizer. The code
 StringTokenizer st = new StringTokenizer("this is a demo");
     while (st.hasMoreTokens( )) {
         System.out.println(st.nextToken( ));
     }

prints the following output:
 this
 is
 a
demo

Some of the methods of StringTokenizer class are given below :
  1. boolean hasMoreTokens( ) : Tests if there are more tokens available from this tokenizer's string.
  2. boolean hasMoreElements( ) : It returns the same value as the hasMoreTokens method.
  3. String nextToken( ) : It returns the next token from this string tokenizer.


PROGRAM
import java.util.StringTokenizer;
import java.util.Scanner;

class StringTokenizerDemo {

 public static void main(String[] args) {
  
  Scanner s = new Scanner(System.in);
  System.out.println("Enter Sentence =>");
  String str = s.nextLine();
  
  StringTokenizer tokens = new StringTokenizer(str);
  
  System.out.println("Tokens are=> ");
  while(tokens.hasMoreTokens())
  {
   System.out.println(tokens.nextToken());
  }
 }
}
OUTPUT
C:\>javac StringTokenizerDemo.java
C:\>java StringTokenizerDemo
Enter Sentence =>
This is a StringTokenizer test
Tokens are=> 
This
is
a
StringTokenizer
test

Comments

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.