Wednesday, 26 September 2012

StringTokenizer 
In java, there is a way to break up a line of text into  smaller piece of a string,what are called tokens. This method of breaking up tokens are come from the StringTokenizer class.
In order for the StringTokenizer class to be used, you must import it from a certain library:-

import java.util.*;

example:-

import java.util.StringTokenizer;
public class StringTokenizerExample2{
  public static void main(String args[]){

          String s = "Five+Three=Nine-One";
   String arr[];

          //declare it with 3 tokens as seen above:
   StringTokenizer st = new StringTokenizer(s, "+=-");

   //the array size is the number of tokens in the String:
   arr = new String[st.countTokens()];

          //when there are still more tokens, place it in the array:
   int i = 0;
          while(st.hasMoreTokens()){
  arr[i] = st.nextToken();
                i++;
          }

   //determine the word with the largest length:
          int indexMax = 0;
          for(int i = 1; i < arr.length; i++){
             if(arr[i].length() > arr[indexMax].length())
   indexMax = i;
          }

   System.out.println("The largest element is in index: " 
                + indexMax);

  } //main
} //class

No comments:

Post a Comment