Java Data Type How to - Tokenize String








Question

We would like to know how to tokenize String.

Answer

import java.util.StringTokenizer;
//  w  w w  .j a  va2 s.co  m
public class Main {

  public static void main(String[] args) {
    int i = 0;
    String str = "one);two);three);four";
    StringTokenizer st = new StringTokenizer(str, ");");
    String temp[] = new String[st.countTokens()];

    while (st.hasMoreTokens()) {
      temp[i] = st.nextToken();
      System.out.println(temp[i]);
      i++;
    }
  }
}

The code above generates the following result.