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

String colors= "red,blue,yellow,green";String[] colorArray=colors.split(",");
See also  Redefining Energy Management: Advanced Solutions for Modern Buildings

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist