So my issue here is that I am trying to take in a String from user input, but then I need to convert that string into an array.
So as an example, the user inputted string would be "Hello", and the array (named arr) would be: arr[0]="H" arr[1] = "e" and so on. If anyone can point me in the right direction I would appreciate it a lot!
-
possible duplicate of How do I send a string to a char array in Java?anon– anon2015-06-07 23:51:47 +00:00Commented Jun 7, 2015 at 23:51
-
Please do a search first. This question has been answered before.ratsstack– ratsstack2015-06-07 23:52:40 +00:00Commented Jun 7, 2015 at 23:52
-
possible duplicate of How can I split a String of dots?fabian– fabian2015-06-08 00:02:52 +00:00Commented Jun 8, 2015 at 0:02
Add a comment
|
5 Answers
Use the standard library method:
char[] arr = str.toCharArray();
Documentation: java.lang.String.toCharArray()
Comments
There's a built in function to convert a string to a character array:
String myString = ...;
char[] chars = myString.toCharArray();
If you need each character as a stirng, you can loop over the character array and convert it:
String myString = ...;
String[] result = new String[myString.length];
char[] chars = myString.toCharArray();
for (int i = 0; i < chars.length; ++i) {
result[i] = String.valueOf(chars[i]);
}
Comments
Read javadoc: String - toCharArray method
public char[] toCharArray() Converts this string to a new character array.
Comments
You can use String.split("") like
String[] arr = str.split("");
That will give you an array arr where each substring is one character
[H, e, l, l, o]
Another option might be String.toCharArray() if a char[] is acceptable like
char[] arr = str.toCharArray();