StringTokenizer countTokens() returns 1 with any string

流过昼夜 提交于 2019-12-13 07:59:07

问题


Here is my code:

StringTokenizer line = new StringTokenizer("{([]{()})({})}");
System.out.println("Count: " + line.countTokens());

The output is always Count: 1

I know this shouldn't he happening with such a simple code. Could there be something wrong with the StringTokenizer library?

Please help!


回答1:


The default delimiter set of a StringTokenizer includes only whitespace characters, which aren't present in your string.

http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html#StringTokenizer%28java.lang.String%29

Also note the following statement from the JavaDoc of StringTokenizer:

"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."




回答2:


to print the next token, use System.out.println(line.nextToken());



来源:https://stackoverflow.com/questions/27583883/stringtokenizer-counttokens-returns-1-with-any-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!