Friday, December 27, 2024
Google search engine
HomeLanguagesJavaStringTokenizer Methods in Java with Examples | Set 2

StringTokenizer Methods in Java with Examples | Set 2

StringTokenizer class in Java is used to break a string into tokens. One must go through StringTokenizer class where concepts and constructors are discussed which help in better understanding  methods that are been discussed here below as follows:

Methods of StringTokenizer class are as follows:

  • hasMoreToken
  • nextToken
  • countTokens
  • nextElement
  • hasMoreElements

Method 1: hasMoreTokens()

The method plays role in testing if tokens are present for the StringTokenizer’s string. Those characters that are considered to be delimiters by the StringTokenizer object are changed to characters in the string delimiter. Then the next token to the current position in the string is returned. 

Syntax:

public boolean hasMoreTokens()

Return Type: A boolean value, true if and only if next token to the current position in the string exists, else false.

Method 2: nextToken()

The method returns the next token from the given StringTokenizer. 

Syntax:

public String nextToken()

Return Type: The next token from the given StringTokenizer if present.

Exception Thrown: NoSuchElementException if no more tokens are left.

Method 3: countTokens()

The method returns the total number of tokens present so that we can use nextToken() method before it gives an exception.

Syntax:

public int countTokens()

Return Type: the number of tokens remaining in the string using the current delimiter set.

Example 

Java




// Java Program to Illustrate Methods of StringTokenizer class
// Via hasMoreToken(), nextToken() and countTokens()
 
// Importing required classes
import java.util.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String args[]) {
         
        // Input strings
        String mydelim = " : ";
        String mystr = "JAVA : Code : String : Tokenizer : Geeks";
 
        // Use of Constructor 2
        // Here we are passing Delimiter - "mydelim"
        StringTokenizer geeks3 =
            new StringTokenizer(mystr, mydelim);
 
        // Printing count of tokens and tokens
        // using countTokens() method
        int count = geeks3.countTokens();
        System.out.println("Number of tokens : " + count + "\n");
 
        // Iterating to get the tokens
        for (int i = 0; i < count; i++)
            System.out.println("token at [" + i + "] : "
                               + geeks3.nextToken());
 
        // checks for more tokens using hasMoreTokens() method
        // which holds true till there is single element remaining
        while (geeks3.hasMoreTokens())
 
            // Returning the next token
            // using nextToken() method
            System.out.println(geeks3.nextToken());
    }
}


Output

Number of tokens : 5

token at [0] : JAVA
token at [1] : Code
token at [2] : String
token at [3] : Tokenizer
token at [4] : Geeks

Method 4: nextElement()

The method works similar to nextToken except that it returns an Object rather than String. Exists so that this class can implement the Enumeration interface. 

Syntax:

public Object nextElement()

Return Type: the next token from the given StringTokenizer.

Exception Thrown: NoSuchElementException if there are no more tokens left.

Method 5: hasMoreElements()

This method returns the same value as hasMoreToken. It exists so that the class can implement the Enumeration interface. 

Syntax:

public boolean hasMoreElements()

Return Type: A boolean value, true if tokens are present in the string, else false

Example 

Java




// Java Program to Illustrate Methods of StringTokenizer
// Class Via hasMoreElements, nextElement and nextElement
 
// Importing required classes
import java.util.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Input strings
        String mydelim = " : ";
        String mystr
            = "JAVA : Code : String : Tokenizer : Geeks";
 
        // Use of Constructor 2
        // Here we are passing Delimiter - "mydelim"
        StringTokenizer geeks
            = new StringTokenizer(mystr, mydelim);
 
        // Counting no. of tokens present
        // using countTokens() method
        int count = geeks.countTokens();
 
        // Printing no. of tokens present
        System.out.println("Number of tokens : " + count);
 
        //  Condition holds true till there is
        // single token remaining using hasMoreElements()
        // method True if tokens are present
        while (geeks.hasMoreElements())
 
            //  Returning the next token
            // using nextElement() method
            System.out.println(geeks.nextElement());
    }
}


Output

Number of tokens : 5
JAVA
Code
String
Tokenizer
Geeks

Tip: Do remember certain important points as listed:

  • countTokens() method is a good alternative in using the combination hasMoreTokens() and nextToken().
  • The combination of countTokens() and nextToken() is used if you are interested in the number of tokens also.

This article is contributed by Mohit Gupta. If you like Lazyroar and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the Lazyroar main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 

RELATED ARTICLES

Most Popular

Recent Comments