Converting String to "Character" array in Java
To convert a string to a character array in Java, you can use the toCharArray
method of the String
class. This method returns a new character array that represents the same sequence of characters as the string.
Here's an example of how you can use the toCharArray
method:
String s = "hello";
char[] charArray = s.toCharArray();
The charArray
variable will now be an array with the following elements: ['h', 'e', 'l', 'l', 'o']
.
Alternatively, you can use the String
class's charAt
method to manually loop through the characters in the string and add them to an array:
String s = "hello";
char[] charArray = new char[s.length()];
for (int i = 0; i < s.length(); i++) {
charArray[i] = s.charAt(i);
}
I hope this helps! Let me know if you have any questions.