Friday, March 29, 2013

StringTokenizer Example

StringTokenizer Example:

StringTokenizer is the class in java.util package.

The use of StringTokenizer class is breaks the given string into number of tokens based on the delimiter.

Here i am giving the very simple StringTokenizer Example. you can easily understand the below code.

In the below example, i am using the delimiter as ';'

While creating the StringTokenizer object I am passing the given string and the delimiter.

By using the countTokens() method, will get the total number of tokens.

String Tokenizer Sample code

 import java.util.StringTokenizer;  
 /**  
  * Java String Tokenizer example  
  */  
 public class StringTokenizerExample {  
      public static void main(String[] args) {  
           String str = "value1;value2;value3;value4";  
           StringTokenizer stringTokenizer = new StringTokenizer(str, ";");  
           //return the total number of tokens  
           int totalTokens = stringTokenizer.countTokens();  
           System.out.println("Total Tokens " + totalTokens);  
           //Iterate and print all the tokens  
           while (stringTokenizer.hasMoreElements()) {  
                System.out.println(stringTokenizer.nextElement());  
           }  
           //You can use the below method also to print the tokens.  
           // while(stringTokenizer.hasMoreTokens()){  
           // System.out.println(stringTokenizer.nextToken());  
           // }  
      }  
 }  


Output :


Total Tokens 4
value1
value2
value3
value4


You can also use split method to split the given string into number of tokens.

String[]   tokens = str.split(";");


0 comments:

Post a Comment

 
Disclaimer : If you find any mistakes / corrections / feedback Please let us know...This website author shall not accept liability or responsibility for any errors, mistakes or misstatements found in this website.