Menu
Topics Index
...
`

String Tokenizer Demo - Java Example Program


String Tokenizer Demo
import java.util.StringTokenizer;

class StringTokenizerDemo
{
    public static void main(String arg[])
    {
        StringTokenizer st1 = new StringTokenizer("Welcome to Merit" +
                        " Campus."); // LINE A
        while (st1.hasMoreTokens()) {
            System.out.println(st1.nextToken());
        }
        System.out.print("---------\n");
        StringTokenizer st2 = new StringTokenizer("It's an,Education," +
                "Website.", ","); // LINE B
        while (st2.hasMoreTokens()) {
            System.out.println(st2.nextToken());
        }
        System.out.print("---------\n");
        StringTokenizer st3 = new StringTokenizer("Learn~programming~with Java.",
                "~", true); // LINE C
        while (st3.hasMoreTokens()) {
            System.out.println(st3.nextToken());
        }    
    }
}
OUTPUT

Welcome
to
Merit
Campus.
---------
It's an
Education
Website.
---------
Learn
~
programming
~
with Java.

DESCRIPTION

In LINE A the StringTokenizer breaks the String "Welcome to Merit Campus." into tokens and the tokens are printed. In LINE B the StringTokenizer breaks the String "It's an, Education, Website." into tokens using "," as a delimiter and the tokens are printed. In LINE C the StringTokenizer breaks the String "Learn, programming, with Java." into tokens using "," as a delimiter, includes the delimiter as returnDelims flag is true and the tokens are printed.

THINGS TO TRY
  • Try using hasMoreElements() and countTokens() instead of hasMoreTokens() to check for tokens.
  • Try using nextElement() instead of nextToken() to retrieve the next token.
  • Try using nextToken() along with a delimiter to retrieve the next token of the string tokenzier's string.

© meritcampus 2019

All Rights Reserved.

Open In App