总之,这段代码是一个空格分隔的分词器,它将字符串分成三个部分。
因此,在这个特定示例中,s1、s2 和 s3 的值将是:
s1 = "You";
s2 = "are";
s3 = "cool";
要查看存储在其中的值,只需执行以下操作:
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
现在,至于为什么?
看到这个:
String s1, s2, s3="";//these are the strings that will hold the sub tokens
StringTokenizer line = new StringTokenizer("You are cool");//this initializes an object of the StringTokenizer class with a string value of "You are cool"
s1 = line.nextToken();//this reads up until the first whitespace character (which will be skipped)
s2 = line.nextToken();//this will read from the last position of the iterator
//this will continue reading tokens (delimited by whitespace) from the initialized
//StringTokenizer, (now at the position after "are"):
while (line.hasMoreTokens())
s3 +=line.nextToken();//and those tokens are **appended** to s3! Note appended! Not stored in or overwritten to!
因此,声称*this 程序最多对字符串进行 3 次标记(通过空格)。
但是,你应该被警告:因为在 StringTokenizer 被初始化为这个的情况下:
"You are cool, bro"
(注意空格后面的额外空格和字符)
你会得到这个:
s1 = "You";
s2 = "are";
s3 = "cool,bro";//note the lack of whitespace!
最后一部分来自于在while循环中:
while (line.hasMoreTokens())
s3 +=line.nextToken();//a nextToken() call skips over whitespace by default
因此,无论有多少, s3 都会从 追加下一个标记。line