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.
Answer from rsp on Stack OverflowTo 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.
What is a string in Java?
Can we convert a string into a list instead of an array?
How to handle empty strings when converting to an array?
I believe this could be solved using String#split.
String[] lettersOfHello = "hello".split("");
Will need to circle back if it is preinstalled in Java 8 or no introduced until a later package.
Here's a solution that:
- doesn't use any imports – except for
java.util.Arraysso that it can print out the character array for verification, but that's only for this answer, doesn't have anything to do with the code solution itself. - builds an array of Character, and not
java.lang.Stringas you posted in your code – your expected output["h", "e", "l", "l", "o"]could be an array of Strings (double-quotes) but also looks like it would work as characters
import java.util.Arrays;
String s = "hello";
Character[] chars = new Character[s.length()];
for (int i = 0; i < s.length(); i++) {
chars[i] = s.charAt(i);
}
System.out.println("chars[]: " + Arrays.toString(chars));
Here's the output:
chars[]: [h, e, l, l, o]