Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using StringTokenizer and String.split( )? [duplicate]

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.

like image 438
Satyendra Avatar asked Oct 30 '13 09:10

Satyendra


2 Answers

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]);
like image 153
MadProgrammer Avatar answered Sep 17 '22 15:09

MadProgrammer


String#split accepts a regular expression whether StringTokenizer just accepts a String by which will split the string. You should always stick to the String#split, it's more robust then StringTokenizer.

like image 34
Petr Mensik Avatar answered Sep 18 '22 15:09

Petr Mensik