• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Alternative to StringTokenizer

 
Bhushan Shete
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there any alternative ( other than substring ) that can be used instead of StringTokenizer ???
Actually, I am facing a problem with StringTokenizer. If I have a string with a character '=' in it, then the following code results in false tokens :
StringTokenizer valToken = new StringTokenizer(val,"==>");
while(valToken.hasMoreTokens())
{
valno = valToken.nextToken();
valdate= valToken.nextToken();
}

 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is not really a servlets and JSP question, so I've moved it to Java in General (intermediate)
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you pass a second (String) argument to StringTokenizer, the characters in the String are considered individually, not together. Meaning it will not look for the pattern "==>" but rather for an individual '=' or '>'. Having two of the same character in the String is redundant, but not an error. If what you really want is to find the pattern "==>" but not lone '=' and '>' chars, use the indexOf() method in String:
<code><pre>
int pos = val.indexOf("===>");
if (pos < 0) {<br /> System.out.println("Not found");<br /> }<br /> else {<br /> System.out.println("Before: " + val.substring(0, pos));<br /> System.out.println("After: " + val.substring(pos + 3));<br /> }<br /> </pre></code><br /> To get more of the behavior of StringBuffer, you may want to construct a loop that will look for successive occurrences of the "==>" substring.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And now I see you've posted the same question in Java in General (Advanced), so I'm closing this thread. Please don't waste people's time by posting the same question in multiple forums; I hate to spend time answering a question that's already been done.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic