• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Converting String to an array.

 
Bhasker Reddy
Ranch Hand
Posts: 176
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a String like
String param = "invoice number, file name, userid";
How do i convert this into an array and extract each values,
My String param can contain sometimes 3 words(with comma separated) or sometimes 5 or 2 , i get param dynamically.
can anyone suggest what to do
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
what you can do is the following:

HIH
Val
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excuse me I think I did not quite answer your question...
The best way to extract tokens from a String object is with a StringTokenizer object, for instance:

All tokens of the initial String are now contained in the String array named "tokens".
HIH
Val
 
Bhasker Reddy
Ranch Hand
Posts: 176
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want my array to be like this
String arr[] = {"invoice number", "file name", "userid" }
not individual characters
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this code prints:
invoice number
file name
userid


hope helps
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oops...
I din't see the previous post
 
Bhasker Reddy
Ranch Hand
Posts: 176
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Guys
i got it
 
Roopa Bagur
Ranch Hand
Posts: 267
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you do a toCharArray the commas are also stored in the elements to avoid this use StringTokenizer with comma as the delimiter.
For example:
String[] s = new String[10];
String param = "invoice number, file name, userid";
StringTokenizer st = new StringTokenizer(param,",");
int i = 0;
while (st.hasMoreTokens())
{
s[i]= st.nextToken();
System.out.println("String[] elements:"+s[i]);
i++;
}
I hope your requirements were met.
Roopa.
Originally posted by Bhasker Reddy:
I have a String like
String param = "invoice number, file name, userid";
How do i convert this into an array and extract each values,
My String param can contain sometimes 3 words(with comma separated) or sometimes 5 or 2 , i get param dynamically.
can anyone suggest what to do

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic