Home arrow static arrow Java Programming [Archive] - StringTokenizer Issue
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - StringTokenizer Issue
This topic has 4 replies on 1 page.

Posts:21
Registered: 11/20/03
StringTokenizer Issue  
Jun 21, 2004 4:16 PM



 
The output of the following program

import java.util.StringTokenizer;
public class TestToken {
public static void main(String[] args) {
String strMy = "abcd|^|xyz|^|ac|DE|^|1234";
StringTokenizer strToken = new StringTokenizer(strMy, "|^|");
System.out.println("Total tokens : " + strToken.countTokens());
while (strToken.hasMoreTokens())
System.out.println(strToken.nextElement().toString());
}
}

is
Total tokens :5
abcd
xyz
ac
DE
1234

Actually what I expect is
Total tokens :4
abcd
xyz
ac|DE
1234

Am I missing anything?
Please help.
 

Posts:1,183
Registered: 1/23/02
Re: StringTokenizer Issue  
Jun 21, 2004 4:24 PM (reply 1 of 4)



 
Am I missing anything?

Yes. Each character in the second argument to StringTokenizer(String, String) is a delimeter, not the string as a whole.

On JDK 1.4+ see String.split() for an alternative.
 

Posts:21
Registered: 11/20/03
Re: StringTokenizer Issue  
Jun 21, 2004 4:55 PM (reply 2 of 4)



 
Yeah got what you meant. Tried with an example. It considers whatever character available in the second string argument as a potential delimitter. If we have the second argument as "abcde", then any occurrence of characters 'a' or 'b' or 'c' or 'd' or 'e' in the first argument, will get tokenized.

Thanks a lot.
Venkat
 

Posts:24,517
Registered: 98-02-27
Re: StringTokenizer Issue  
Jun 21, 2004 7:05 PM (reply 3 of 4)



 
You could use [url http://www.discoverteenergy.com/files/SimpleTokenizer.java]SimpleTokenizer[/url] which can take a string as a single delimiter.
 

Posts:2,391
Registered: 9/26/00
Re: StringTokenizer Issue  
Jun 22, 2004 8:15 AM (reply 4 of 4)



 
Here's how you would do it using split():
public class TestToken{  public static void main(String[] args)  {    String strMy = "abcd|^|xyz|^|ac|DE|^|1234";     String[] tokens = strMy.split("\\|\\^\\|");     int len = tokens.length;    System.out.println("Total tokens : " + len);    for (int j = 0; j < len; j++)    {      System.out.println(tokens[j]);    }  }}
 
This topic has 4 replies on 1 page.