开发者

how to convert string in string array? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 11 开发者_C百科years ago.

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 Lists 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"};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜