Easy Tutorial
❮ Javascript Window Onload Js Sort Table ❯

Java StringTokenizer Class Usage

Category Programming Technology

Java StringTokenizer belongs to the java.util package and is used to split strings.

StringTokenizer Constructors:

-1. StringTokenizer(String str): Constructs a StringTokenizer object to parse str. The default delimiters in Java are spaces(""), tabs(\t), newlines(\n), and carriage returns(\r).

-2. StringTokenizer(String str, String delim): Constructs a StringTokenizer object to parse str with a specified delimiter.

-3. StringTokenizer(String str, String delim, boolean returnDelims): Constructs a StringTokenizer object to parse str with a specified delimiter, and specifies whether to return the delimiters.

StringTokenizer Common Methods:

-1. int countTokens(): Returns the number of times the nextToken method has been called.

-2. boolean hasMoreTokens(): Returns whether there are more delimiters.

-3. boolean hasMoreElements(): Checks if there is more data in the enumeration object.

-4. String nextToken(): Returns the string from the current position to the next delimiter.

-5. Object nextElement(): Returns the next element in the enumeration object.

-6. String nextToken(String delim): Similar to 4, returns the result with the specified delimiter.

Example 1

import java.util.*;

public class Main 
{ 
    public static void main(String[] args)
    { 
        String str = "tutorialpro,google,taobao,facebook,zhihu";
        // Split the string using the comma as a delimiter
        StringTokenizer st = new StringTokenizer(str, ",");
        while (st.hasMoreTokens()) { 
            System.out.println(st.nextToken());
        }
    }
}

Output:

tutorialpro
google
taobao
facebook
zhihu

Example 2

import java.util.*;

public class Main
{
    public static void main(String args[])
    {
        System.out.println("Using the first constructor:");
        StringTokenizer st1 = new StringTokenizer("Hello tutorialpro How are you", " ");
        while (st1.hasMoreTokens())
            System.out.println(st1.nextToken());

        System.out.println("Using the second constructor:");
        StringTokenizer st2 = new StringTokenizer("JAVA : Code : String", " :");
        while (st2.hasMoreTokens())
            System.out.println(st2.nextToken());

        System.out.println("Using the third constructor:");
        StringTokenizer st3 = new StringTokenizer("JAVA : Code : String", " :", true);
        while (st3.hasMoreTokens())
            System.out.println(st3.nextToken());
    }
}

Output:

Using the first constructor:
Hello
tutorialpro
How
are
you
Using the second constructor:
JAVA
Code
String
Using the third constructor:
JAVA

:

Code

:

String

** Click to Share Notes

Cancel

-

-

-

❮ Javascript Window Onload Js Sort Table ❯