• Post Reply Bookmark Topic Watch Topic
  • New Topic

string tokenizing  RSS feed

 
Lesole Mphinyane
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have a text file with 5 paragraphs which are separated by delimeter '-', the code has to ask the user to enter the paragraph number he/she wishes to read..
How do i go about adding the paragraphs to an array so that when you enter the array index i.e paragraph number, it displays token at given number.....
please help..
 
Jesus Angeles
Ranch Hand
Posts: 2070
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Put your delimiters on the second parameter of the constructor.

*tokenize
StringTokenizer stk = new StringTokenizer(thePhrase,"-");
*load into an array
String[] StrArray = new String[stk.countTokens()];
int i = 0;
while(stk.hasMoreTokens())
{
StrArray[i]=stk.nextToken();
i++;
}
*use as you wish, using the index, starting at 0
System.out.println(StrArray[myIndex]);
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you have the full file content in one string, String.split() (since 1.4) will do the array job for you in one line.

Do you have to wind up with an array or would one of the Collection classes do just as well? You could split as you read and add each paragraph you find to a collection without having to know the size ahead of time as you would with an array. Scanner (since 1.5) would do a real slick job of that.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!