Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
May 29, 2003

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():

String colors= "red,blue,yellow,green";
String[] colorArray=colors.split(",");
Guillermo Labatte
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date