Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

StringTokenizer  RSS feed

 
Zeina Afif
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure if this is a good place to post this q. I'm trying to figure out the best way to parse a resultset containing a string that has more than one value. (like a list of country codes that is stored in a column, seperated by a comma). So far, I've written my own class that goes through the string and creates a string array with the list of country codes.
Would using a StringTokenizer do that for me? Could I specify what delimiter char to use? or is there a better way to deal with this?
'cause after I get the array, I need to go iterate and get the actual country name from the code.
Thanks!
 
Eric Fletcher
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, a StringTokenizer will do that for you. It tokenizes a string based on a delimiter passed as a constructor arg. It implements the Enumeration interface so you loop through an enumeration of tokens.
Example:
If your string is:
String result = "county1, county2, county3";
You could use:
StringTokenizer tokenizer = new StringTokenizer(result, ",", false);
while(tokenizer.hasMoreTokens()){
System.out.println(tokenizer.nextToken());
}
The output would be
county1
county2
county3
the first constructor arg is the string to be tokenized, the second is the string that acts as the delimiter(it can be a longer string, not just a single character string), and the last arg is a boolean telling the tokenizer whether you want the delimiter in the resulting token(int this case, no).
Hope that helps.
Cheers
E
 
Zeina Afif
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Eric, that's exactly what I wanted to know.
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As a general comment, you should be careful with StringTokenizer and comma-separated columns.
Consider the case "a,b,c,,e,f"
"Common sense" says that there are six columns:
"a" "b" "c" "" "e" "f"
StringTokenizer says that there are only five:
"a" "b" "c" "e" "f"
StringTokenizer has the sometimes-irritating habit of lumping all the separators together, so beware!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!