This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
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.
Originally posted by Mingwei Jiang: I read one line from the file that is separated by tab, and no matter I use "\t" or " " (tab in double quotes), it doesn't work. It can only give me one token instead of 12 which is correct.
Can anyone help me?
I don't see anything wrong with this code. Are you sure that line has tab characters in it? Also, are there any characters in between the tab characters. If for example, you have something like [code] String line = "\t\tsomething" [code] Then StringTokenizer will only return a single token. By default it will not return the "null token" between the two tab characters. I believe there is a method to force it to do so, however.
With that said, I agree that you should use String.split() or regular experessions instead, if you are using a version of Java that supports these.
On the lines of split. Is there an opposite? Like join? In php there is explode and implode. Of course you can do the implode in Java through a loop, but is there something like String.join(String , delimiter)?? Yes I did check the String API. There is no String.join per see, but maybe someone knows a particular API that does include this.
Joined: Dec 06, 2001
I don't know of this anywhere in the API, but that doesn't mean much. You should be able to write a method that does this using StringBuilder fairly easily.