简体   繁体   中英

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:

msg1 shows New but should be New record created successfully
msg2 shows stops but should be Enter stops

A StringTokenizer splits the string at each position of all supplied characters in the delimiter argument. 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.

Use String#split which takes a regular expression that is used to tokenise the string:

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:

New Record created successfully
Enter stops

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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