converting a string into array of strings
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Anonymous
Posted On:   Saturday, May 31, 2003 02:09 PM

I need to convert a simple string es:  String s= "dog,cat,car,soap"

into a array of string as:      String strings[]={"dog","cat","car","soap"};


Can you help me showing a sample ?


thanks

Re: converting a string into array of strings

Posted By:   Jeanne_Boyarsky  
Posted On:   Sunday, June 1, 2003 10:07 AM

If you are using Java 1.4, there is a method that does this already.
String result = s.split(",");

Re: converting a string into array of strings

Posted By:   AlessandroA_Garbagnati  
Posted On:   Saturday, May 31, 2003 02:33 PM

Ciao Pier Luigi,

The class you should use is java.util.StringTokenizer and the StringTokenizer JavaDoc does show you few examples on how to parse/split a string.

This is a simple example. I have written it "on the fly" so if there are errors, please do excuse me...

...
String str = "uno,due,tre,quattro";
StringTokenizer st = new StringTokenizer(str, ",");
String[] strArr = new String[st.countTokens();
int counter = 0;
while (st.hasMoreTokens()) {
strArr[counter++] = st.nextToken();
}
...
About | Sitemap | Contact