File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes String Tokenizer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String Tokenizer" Watch "String Tokenizer" New topic

String Tokenizer


Joined: Feb 12, 2001
Posts: 2
Hi folks,
During the use of the StringTokenizer class, I came across a string in the format "1","ABC","Last, First","CAT","MBA"
If i use the comma as a my delimiter, how do I handle the "," in inside the double quoted string? Especially when I do a countTokens(), it returns 6 tokens instead of 5.
Any help would be greatly appreciated.
Frank Carver

Joined: Jan 07, 1999
Posts: 6920
The Java Ranch has thousands of visitors every week, many with surprisingly similar names. To avoid confusion we have a naming convention, described at . We require names to have at least two words, separated by a space, and strongly recommend that you use your full real name. Please log in with a new name which meets the requirements.

Read about me at ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
John Bateman
Ranch Hand

Joined: Mar 09, 2000
Posts: 320
I Since everything is a string in your example..
use "," as the 'token'.. BUT, you will have to use indexOf to get a position of each token and then subString() the token out of the String. This is because the StringTokenizer will consider the "," as a list of tokens to check for.
Would give you 3 tokens.
token 1> "Hi
token 2> there
token 3> me, you"
Now all you have to do is chop the 1st char off the 1st token and the last char off the last token.
Just my $0.02cdn

SOURCE CODE should be SURROUNDED by "code" tags.
Art Metzer
Ranch Hand

Joined: Oct 31, 2000
Posts: 241
Here's all I could think of, and I of course defer to any better solutions.
1. Go through your original String, replacing all commas between quotes with a placeholder character that you can guarantee will never ever appear in any input String.
2. Tokenize this altered String.
3. When you receive each token, replace each placeholder you find with a comma.
4. Process the token normally.
Here's a bit of code to demonstrate:

Will something like this do the trick?
[This message has been edited by Art Metzer (edited April 06, 2001).]
Angela Jessi
Ranch Hand

Joined: Nov 27, 2000
Posts: 428
I think you can use indexOf. Then get the length of string.
Here is an example:
int iLen;
iEnd = sToken.indexOf(':', iEnd);
sTemp = sToken.substring(iBegin, iEnd);
iBegin = iEnd + 1;
if( iFlag == 1 ) // Parsing to get the values of arguments
iLen = Integer.parseInt(sTemp);
sTemp = sToken.substring(iBegin, iBegin + Len);
iEnd = iBegin + iLen + 1;
iBegin = iEnd;
return sTemp;

I agree. Here's the link:
subject: String Tokenizer
It's not a secret anymore!