Difference between using StringTokenizer and String.split( )?

Satyendra picture Satyendra · Oct 30, 2013 · Viewed 45.3k times · Source

I've been using String[] split(String) of String class to split any string for some given delimiter, and it worked fine.

However, now it is expected to re-factor the same logic with StringTokenizer. But what are the differences and benifits of using one over the other.

Also, I feel that String[] returned by split() in a single call is much efficient option than using the objects of the class StringTokenizer.

Answer

MadProgrammer picture MadProgrammer · Oct 30, 2013

Take a look at the JavaDocs

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

The following example illustrates how the String.split method can be used to break up a string into its basic tokens:

 String[] result = "this is a test".split("\\s");
 for (int x=0; x<result.length; x++)
     System.out.println(result[x]);