String Tokenizer in Java I

You may come across a situation where in small string has to be parsed with respect to some delimiters instead of entire file.

Wait.. Don't just jump to code by looking character by character...that's tedious to do..isn't it?

Be smart enough to use well defined and built in classes & methods which serve your purpose :-)

I am telling about "java.util.StringTokenizer" class! Lets understand its capacity with a small example...


package org.chandan.string.tokenizer;

import java.util.StringTokenizer;

public class StringTokenizerSample {

   //Your String to be tokenized.
   private static final String SAMPLE_STRING_1=
   "a1,A2,a3,A4,a5";

   //delimiter used to tokenize.
   private static final String DELIM_COMMA=",";

   public static void main(String args[])
   {
     System.out.println("PROCESSING STRING = ["+SAMPLE_STRING_1+"]");
      System.out.println("----------------------------------------");

     processString(SAMPLE_STRING_1,DELIM_COMMA);

     System.out.println("");
     System.out.println("*********************************************");
  }

  private static void processString(String sample,String delimiters)
  {
      StringTokenizer stringTokenizer=new StringTokenizer(sample,delimiters);
      System.out.println("TOTAL NO OF TOKENS FOUND: "
      +stringTokenizer.countTokens());
      int tokenCount=1;

     while(stringTokenizer.hasMoreElements())
    {
       System.out.println("TOKEN["+tokenCount+"] = "
       +stringTokenizer.nextElement());
    }
  }

}


OUTPUT:

PROCESSING STRING = [a1,A2,a3,A4,a5]
----------------------------------------
TOTAL NO OF TOKENS FOUND: 5
TOKEN[1] = a1
TOKEN[2] = A2
TOKEN[3] = a3
TOKEN[4] = A4
TOKEN[5] = a5

*********************************************


If you are looking for some tutorials on parsing an xml document, then check HERE.

Still hungry...? Check next post on Tokenizer here

Got doubts ? Post as comments....Lets find solution together!
Happy coding :)


.

No comments:

Post a Comment