• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can StringTokenizer ignore whitespace??

 
Sair Legge
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to read and separate a comma separated list, but I only want the StringTokenizer to use the comma to separate the words and not whitespace. I set the code as:
String text = "black white,blue green"
StringTokenizer st = new StringTokenizer(myString, ",");
String[] list = new String[2];
int count = 0;
while (st.hasMoreTokens()){
list[count] = st.nextToken();
count++;
}
I want "black white" to go into list[0], and "blue green" to go into list[1], however the StringTokenizer still separates the list on white spaces as well as the commas, and I end up with an IndexOutOfBoundsException occuring.
Any suggestions???
 
Thomas Bigbee
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sair Legge:
I want to read and separate a comma separated list, but I only want the StringTokenizer to use the comma to separate the words and not whitespace. I set the code as:
String text = "black white,blue green"
StringTokenizer st = new StringTokenizer(myString, ",");
String[] list = new String[2];
int count = 0;
while (st.hasMoreTokens()){
list[count] = st.nextToken();
count++;
}
I want "black white" to go into list[0], and "blue green" to go into list[1], however the StringTokenizer still separates the list on white spaces as well as the commas, and I end up with an IndexOutOfBoundsException occuring.
Any suggestions???
- the below code works - you had a few typos
- notice that myString has been replaced by text
- and the System.out.println() to test the output
String text = "black white,blue green";
StringTokenizer st = new StringTokenizer(text, ",");
String[] list = new String[2];
int count = 0;
while (st.hasMoreTokens())
{
list[count] = st.nextToken();
System.out.println(list[count]);
count++;
}

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic