1

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

Matt
  • 12,848
  • 2
  • 31
  • 53
pintu
  • 11
  • 4
  • *FYI:* The javadoc of [`StringTokenizer`](https://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html) says: *"`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."* – Andreas Jan 10 '21 at 10:39

1 Answers1

1

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
Matt
  • 12,848
  • 2
  • 31
  • 53