This question already has an answer here:
- Scanner vs. StringTokenizer vs. String.Split 10 answers
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
.
I have the following program,
The string "x" is a tab separated 12s34;
String#split
accepts a regular expression whetherStringTokenizer
just accepts aString
by which will split the string. You should always stick to theString#split
, it's more robust then StringTokenizer.Take a look at the JavaDocs
->
String.split()
andPattern.split()
give you an easy syntax for doing the latter, but that's essentially all that they do. If you want to parse the resulting strings, or change the delimiter halfway through depending on a particular token, they won't help you with that.->
StringTokenizer
is even more restrictive thanString.split()
, and also a bit fiddlier to use. It is essentially designed for pulling out tokens delimited by fixed substrings. Because of this restriction, it's about twice as fast asString.split()
. (See my comparison ofString.split()
andStringTokenizer
.) It also predates the regular expressions API, of whichString.split()
is a part.You'll note from my timings that
String.split()
can still tokenize thousands of strings in a few milliseconds on a typical machine. In addition, it has the advantage overStringTokenizer
that it gives you the output as a string array, which is usually what you want. Using anEnumeration
, as provided byStringTokenizer
, is too "syntactically fussy" most of the time. From this point of view,StringTokenizer
is a bit of a waste of space nowadays, and you may as well just useString.split()
.Answer from this link
http://docs.oracle.com/javase/6/docs/api/java/util/StringTokenizer.html say:
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.
So I would say, don't change it and show that line to the person who recommended refactoring it. Maybe they have old information or another good reason to tell you.
Read this
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.