Java StringTokenizer class

    StringTokenizer class

    Java uses the class java.util.StringTokenizer that allows the string to break into tokens which are considered to be the simple way to break strings. But you cannot differentiate the numbers, quoted strings etc. this class uses three constructors that are mentioned below-

    • StringTokenizer(String str)-it will create the StringTokenizer with the provided string.
    • StringTokenizer(String str, String delim)- it will create the StringTokenizer with given string and delimiter.
    • StringTokenizer(String str, String delim, boolean returnValue)- it will create the StringTokenizer with specified string, delimiter and returnValue. If the return value is true then the delimiter characters are used as tokens but if false then the delimiter characters will be used as separate tokens.

    Methods of StringTokenizer class-

    • boolean hasMoreTokens()- this method will check if there are more tokens available.
    • String nextToken()- this method will return the next token from the StringTokenizer object.
    • String nextToken(String delim)- this method will return the next token based on the delimiter.
    • boolean hasMoreElements()- it is as same as the hasMoreTokens() method.
    • Object nextElement()- it is as same as the nextToken() but its return type is Object.
    • int countTokens()- this method will return the total number of tokens.

    Example-

    import java.util.StringTokenizer;  
    
    public class Simple{  
    
     public static void main(String args[]){  
    
       StringTokenizer st = new StringTokenizer("how are you man"," ");  
    
         while (st.hasMoreTokens()) {  
    
             System.out.println(st.nextToken());  
    
         }  
    
       }  
    
    } 

    Output-

    nextToken() method example-

    import java.util.StringTokenizer;  
    
    public class Simple{  
    
       public static void main(String[] args) {  
    
           StringTokenizer st = new StringTokenizer("how,are,you,man");  
    
           
    
          System.out.println("Next token is : " + st.nextToken(","));  
    
       }      
    
    }  

    Output-

    Java next token method