Abbey Workshop

Java: Splitting a String

Click on the following link to to see the sample code for splitting a string a part using the StringTokenizer class.

SplitString.java

   1:import java.util.*;
   2:/**
   3: *  This class demonstrates how to use the StringTokenizer class to splitt apart
   4: *  strings of text.
   5: */
   6:class SplitString {
   7:
   8:    public static void main(String[] arguments) {
   9:        StringTokenizer ex1, ex2; // Declare StringTokenizer Objects
  10:        int count = 0;
  11:
  12:        String strOne = "one two  three      four   five";
  13:        ex1 = new StringTokenizer(strOne); //Split on Space (default)
  14:
  15:        while (ex1.hasMoreTokens()) {
  16:            count++;
  17:            System.out.println("Token " + count + " is [" + ex1.nextToken() + "]");
  18:        }
  19:
  20:        count = 0;  // Reset counter
  21:        
  22:        String strTwo = "item one,item two,item three,item four"; // Comma Separated
  23:        ex2 = new StringTokenizer(strTwo, ",");  //Split on comma
  24:
  25:        while (ex2.hasMoreTokens()) {
  26:            count++;
  27:            System.out.println("Token " + count + " is [" + ex2.nextToken() + "]");
  28:        }
  29:    }
  30:}

C:\java\examples>java SplitString
Token 1 is [one]
Token 2 is [two]
Token 3 is [three]
Token 4 is [four]
Token 5 is [five]
Token 1 is [item one]
Token 2 is [item two]
Token 3 is [item three]
Token 4 is [item four]

Line 12 shows the first string to be parsed. Notice there a number of spaces between a couple of the items. Line 13 splits up the string. By default, the delimiter is a space and any extra spaces are automatically removed. Lines 15 - 18 show all parsed elements are walked through using the nextElement() method.

Lines 22 and 23 show how an alternative delimiter is specified when the StringTokenizer object is specified.