• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

StringTokenizer takes only single char: pl help!

 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi friends,
Why does the following code prints "how are you, "why are you" and "im fine". Should it print "how are you# why are you" and then "im fine". Can't strintokenixer tokenize with two characters.
How can i achive this.
String test = "how are you# why are you## im fine";
StringTokenizer str = new StringTokenizer(test, "##");
while(str.hasMoreElements())
{
System.out.println("The string is:" + str.nextToken());
}
Thanks a lot in advance.
cheers
rajat
 
Ranch Hand
Posts: 338
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Rajat,
Read the javadoc for StringTokenizer. The string for the second parameter is a list of all characters that will be treated as delimiters. If you want to match a pattern as a delimiter for the tokens, you need to use something else.
 
Rajat Singla
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks andrew.
But what's the alternative? How can i solve the problem.
regs
rajat
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
<pre>
String test = "one#two##three##four#five";
String[] tokens = test.split("##");
for (int i = 0; i < tokens.length; i++) {
System.out.println("Token " + i + ":" + tokens[i]);
}
</pre>
Of course, if you aren't using SDK 1.4, you'll have to write a little more code. Try using String indexOf("##") to locate a multi-character delimiter, and then use substring() to split the string before and after the delimiter. Put the whole thing in a loop to find more than one delimiter. Enjoy...
 
They weren't very bright, but they were very, very big. Ad contrast:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic