how to convert string in string array? [closed]
suppose I am getting 2 strings
"About product" and "About Us"
and I want to store them in String
array like
myArray[]={"About product", "About Us"};
how to do this?
The code you've shown at the end is almost correct already. If you're declaring the variable at that point you can use:
String[] myArray = { firstString, secondString };
Otherwise (if it's declared elsewhere) you can use:
myArray = new String[] { firstString, secondString };
If this isn't what you're trying to achieve, please clarify your question.
You are reading strings dynamically, and you want to end up with an array of them (String[]
), but you don't know how many there are until you've read them all.
In Java, arrays are of fixed length, so the answer is not to store them in an array until you know how many there are. What you need is a temporary list. There are several lists you can use, depending upon certain performance characteristics, but the ArrayList
is a reasonable choice.
ArrayList<String> arrList = new ArrayList<String>();
will create a new array list. Then in a loop you can read a string and add it to the list (which will expand to accommodate each new entry):
arrList.add(str);
and then you can create and fill the array you really wanted. There is a convenience method on List
s for doing this, like this:
String[] strArray = arrList.toArray(new String[arrList.size()]);
It is not obvious at first glance why the toArray
method needs to have the array passed to it, but it makes the call typesafe, and you don't have to cast the result to String[]
. You can read the JavaDoc for this method here.
Well, you can do it directly just by doing
String[] myArray={"About product", "About Us"};
If you mean you get the Strings at run time you can just do:
String[] myArray = new String[2];
myArray[0] = s1;
myArray[1] = s2;
String[] myArray = {"About product","About Us"};
精彩评论