string to string array conversion in java
To start you off on your assignment, String.split
splits strings on a regular expression and this expression may be an empty string:
String[] ary = "abc".split("");
Yields the array:
(java.lang.String[]) [, a, b, c]
Getting rid of the empty 1st entry is left as an exercise for the reader :-)
Note: In Java 8, the empty first element is no longer included.
String strName = "name";
String[] strArray = new String[] {strName};
System.out.println(strArray[0]); //prints "name"
The second line allocates a String array with the length of 1. Note that you don't need to specify a length yourself, such as:
String[] strArray = new String[1];
instead, the length is determined by the number of elements in the initalizer. Using
String[] strArray = new String[] {strName, "name1", "name2"};
creates an array with a length of 3.
I guess there is simply no need for it, as it won't get more simple than
String[] array = {"name"};
Of course if you insist, you could write:
static String[] convert(String... array) {
return array;
}
String[] array = convert("name","age","hobby");
[Edit] If you want single-letter Strings, you can use:
String[] s = "name".split("");
Unfortunately s[0] will be empty, but after this the letters n,a,m,e will follow. If this is a problem, you can use e.g. System.arrayCopy in order to get rid of the first array entry.