Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

StringTokenizer problem... 1

Status
Not open for further replies.

brianon

Programmer
Feb 6, 2002
22
0
0
IE
Hi,

I'm trying to parse a string using coma as the delimeter...
Code:
public ParseInputString(String inputString)
    {

        java.util.StringTokenizer st = new java.util.StringTokenizer(inputString, ",");
        parseParameter(st);

        while (st.hasMoreTokens())
        {
            String str = new String(st.nextToken());

            if (str.length() == 0)
            {
                System.out.println("Param : Empty Param");
            }
            else
                System.out.println("Param : "+ str);
        }
    }

If I pass in "Field1,Field2,Field3,Field4" it works fine..

However, if I pass in "Field1,Field2,,Field4"...
I get...
Param : Field1
Param : Field2
Param : Field4

I can't seem to get it to recognize the empty 3rd field.
Is this just how StringTokenizer works ? maybe I need something more complex ?

Regards.
 
Sorry...you can ignore the ...
Code:
parseParameter(st);
...line. Was just trying somehitng out.

Don't know how to edit my post :(
 
You can't edit your post.

Try using the split() method on the inputString instead of the StringTokenizer.

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy
 
String Tokenizer and split are just going to return to you everything that isn't a delimeter.

so if you use ',' as a delimeter then yes, you will get Field1 Field2 and Field4.

Without actually going through each character yourself I don't THINK there is a way to do this. It may be eaiser just do something to the matter of.

Code:
String word = "";
char previous = '';
for(int i = 0; i < inputString.length; i++)
{
  if(inputString.charAt(i) == ',')
  {
    if(previous == ',')
      System.out.println("Param: empty")
    else
      System.out.println("Param: "+word);
    previous = ',';
  }
  else
  {
    previous = inputString.charAt(i);
    word += "" + previous;
  }
}
Or something to that matter
 
You may tell the Tokenizer to return delimiters:

Code:
public StringTokenizer(String str,
                       String delim,
                       boolean returnDelims)
int count = 0;
while (st.hasMoreTokens ())
{
	String str = new String(st.nextToken());
	
	if (str.equals (","))
	{
		++count;
	}
	else System.out.println ("Param " + count + ": " + str);
}
but the split will be more easy and elegant.


seeking a job as java-programmer in Berlin:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top