CodeWorm

Tidbits of code and other items


Google
 
[home]
[java]

How to use the StringTokenizer Class With an Array

  • I got an email this morning (Tuesday, July 26, 2005) from a friend asking me how to turn the StringTokenizer class into an array.  I don't think he really means that.  My guess is that he wants to put the collection created by the StringTokenizer class into an array.

When approaching a problem like this it's a good idea to go to the source.  So, I went to Sun's documentation on the StringTokenizer Class.  Some good sample code is given on Sun's webpage for the StringTokenizer.  They have an example using the Split method from the String Class to do the same thing as the StringTokenizer Class.  It is well worth checking out.  Anyway, here is an example showing the collection created by the StringTokenizer Class placed into an array.

import java.util.*;

public class Test{
  public static void main(String[] args){
    StringTokenizer st = new StringTokenizer("Procrastination is suicide on the installment plan");
    String[] arrayString = new String[st.countTokens()];
    int i = 0;
    while (st.hasMoreTokens()) {
      arrayString[i] = st.nextToken();
      System.out.println(arrayString[i]);
      i++;
    }
  }
}

The output looks like the following:

Procrastination
is
suicide
on
the
installment
plan