devxlogo

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(",");

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  How Seasoned Architects Evaluate New Tech

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.