An Alternative to StringTokenizer

An Alternative to StringTokenizer

Suppose you have a String containing comma-separated substrings. In order to access the substrings individually, you’d normally rely on a StringTokenizer.

And if you wanted to put the substrings in an array you’d write something like this:

 import java.util.StringTokenizer; ... String colors= "red,blue,yellow,green"; StringTokenizer tk= new StringTokenizer(colors, ","); String[] colorArray= new   String[tk.countTokens()]; for (int i= 0; tk.hasMoreTokens(); i++)         colorArray[i]= tk.nextToken();

As of JDK 1.4.0 there is an easier way. Take advantage of the String method split()class="pf">:

String colors= "red,blue,yellow,green";String[] colorArray=colors.split(",");


Share the Post: