StringTokenizer countTokens() returns 1 with any s

2019-09-20 16:33发布

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!

2条回答
来,给爷笑一个
2楼-- · 2019-09-20 16:52

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

查看更多
Juvenile、少年°
3楼-- · 2019-09-20 17:01

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

查看更多
登录 后发表回答