wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Converting String to an array. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Converting String to an array." Watch "Converting String to an array." New topic
Author

Converting String to an array.

Bhasker Reddy
Ranch Hand

Joined: Jun 13, 2000
Posts: 176
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


Bhasker Reddy
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
Hi,
what you can do is the following:

HIH
Val


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
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

Joined: Jun 13, 2000
Posts: 176
I want my array to be like this
String arr[] = {"invoice number", "file name", "userid" }
not individual characters
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
this code prints:
invoice number
file name
userid


hope helps


SCJP2. Please Indent your code using UBB Code
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
oops...
I din't see the previous post
Bhasker Reddy
Ranch Hand

Joined: Jun 13, 2000
Posts: 176
Thanks Guys
i got it
Roopa Bagur
Ranch Hand

Joined: Nov 03, 2000
Posts: 267
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

 
wood burning stoves
 
subject: Converting String to an array.