• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

string tokenizing

 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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..
 
Ranch Hand
Posts: 2108
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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]);
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
I just had the craziest dream. This tiny ad was in it.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic