代码段的说明

时间:2013-04-14 02:33:58

标签: java string stringtokenizer

执行以下代码后,s1,s2和s3的值是什么?

String s1, s2, s3="";
StringTokenizer line = new StringTokenizer("You are cool");
s1 = line.nextToken();
s2 = line.nextToken();
while (line.hasMoreTokens())
    s3 +=line.nextToken();

请注意,这是一个我无法找到的学习指南问题。如果有人能够彻底解释它以便我可以在考试中点燃这类问题,我将不胜感激。

3 个答案:

答案 0 :(得分:1)

总之,这段代码是一个空格分隔的标记器,可以将字符串分成多达三个部分。

因此,在这个特定的例子中,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!

因此,声称 *此程序将字符串标记为最多三次(按空格)。

但是,你应该被警告:因为在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下一个令牌,无论有多少

答案 1 :(得分:0)

字符串s1 s2 s3被实例化为空非空

变量line基本上是一个准备被标记化的新字符串("You are cool")。

每当你执行nextToken()时,它会接受一个字或令牌并将其存储在该变量中

所以这段代码会存储前两个单词。

s1 = line.nextToken();
s2 = line.nextToken();

此代码会查看它们是更多的单词还是标记,它们是(1左)。然后它将获取最后一个标记并将其分配给s3

while (line.hasMoreTokens()) {
    s3 +=line.nextToken();
}

输出方面,程序不是在心理上输出任何东西进入控制台,而是在内存中进行。这就是它在内存中的样子,如果你用System.out.println()输出每个变量。

s1 = "You"

s2 = "are"

s3 = "cool"

答案 2 :(得分:0)

正如@Dukeling所提到的,你可能没有输出,因为你什么都不打印。

另外,请看看这个答案: Why is StringTokenizer deprecated?

从StringTokenizer的javadoc: StringTokenizer是一个遗留类,出于兼容性原因而保留,尽管在新代码中不鼓励使用它。建议任何寻求此功能的人都使用String的split方法或java.util.regex包。

相关问题