Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Java: convert string to array?
i have a list in the form:
item1,item2,item
(separated by comma's only)
i tried to do something like this:
private String listofitems;
private String[] myarray;
listofitems = "item1,item2,item3";
String[] myarray = { listofitems };
but then i call myarray[0] the value i get is 'null' so obviously that don't work...
so what's the simplest way to make this comma-separated list into an array?
Chad: actually if you want to add items to an array you do need to write the [ ] again.
so it is:
String[] array = { "item1", "item2", "itemN" };
2 Answers
- 1 decade agoFavorite Answer
You will need to parse the string yourself, adding the various items to the array one at a time. There may be some faster trick for this, but not that I know of. You will need to know how many items are in the list to set the array size properly. If you don't know this, try using the Java Vector class instead of Array. Or you could use an ArrayList. Both of these are expandable arrays that will not require you to know how many items beforehand. Try this:
import java.util.StringTokenizer;
private int numItems = 3;
private String listofitems;
private String[] myarray = new String[numItems];
listofitems = "item1,item2,item3";
StringTokenizer tokens = new StringTokenizer(listofitems,",");
int i = 0;
while(tokens.hasMoreTokens()) {
myarray[i++] = tokens.nextToken();
}
I haven't tested this code, but it should at least give you an idea of how this works. You can use StringTokenizer to pull out each comma-separated token (these are the items you want to put into the array). Then, while there are more tokens, you put the next token into the appropriate place in the array. Notice that we are incrementing i in the loop by using myarray[i++]. This is just a shortcut. You could move the i++ to the next line and just access myarray[i].
- 1 decade ago
the problem is the way you're adding elements to your array.
it needs to be like this.
private String[] myarray;
then you DO NOT DEFINE String[] again.
myarray = {"item1", "item2", "item3"};