Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

java - 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

question from:https://stackoverflow.com/questions/65651771/unexpected-result-in-stringtokenizer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...