-1

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!

3

5 Answers 5

1

Use the standard library method:

char[] arr = str.toCharArray();

Documentation: java.lang.String.toCharArray()

Sign up to request clarification or add additional context in comments.

Comments

1

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

1

Read javadoc: String - toCharArray method

public char[] toCharArray()
Converts this string to a new character array.

Comments

1
 String hello = "Hello";
 String[] array = hello.split("");

Comments

1

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.