简体   繁体   English

StringTokenizer 中的意外结果

[英]Unexpected result in StringTokenizer

I have the following code which gives me an unexpected result:我有以下代码,这给了我一个意想不到的结果:

String output = "New Record created successfully<br>Enter stops<br>";
StringTokenizer st = new StringTokenizer(output);
token = st.nextToken("<br>");
msg1.setText(token);
while (st.hasMoreTokens()) {
       token = st.nextToken("<br>");
       msg2.setText(token);
}
  

Actual and expected output:实际和预期 output:

msg1 shows New but should be New record created successfully msg1显示New但应该是New record created successfully
msg2 shows stops but should be Enter stops msg2显示stops但应Enter stops

A StringTokenizer splits the string at each position of all supplied characters in the delimiter argument. StringTokenizer分隔符参数中所有提供的字符的每个 position 处拆分字符串。 It does not split at the occurrence of the whole supplied string.它不会在整个提供的字符串出现时拆分。 Besides, it is a legacy class and its usage in new code is not recommended.此外,它是旧版 class,不建议在新代码中使用。

Use String#split which takes a regular expression that is used to tokenise the string:使用String#split ,它采用用于标记字符串的正则表达式:

String output = "New Record created successfully<br>Enter stops<br>";

String[] tokens = output.split("<br>");

String token = tokens[0];
System.out.println(token);
if (tokens.length > 0) {
    token = tokens[1];
    System.out.println(token);
}

Output: Output:

New Record created successfully
Enter stops

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM