Reputation: 153
I'm extremely stuck here. How would I convert a String array to a Char array?
I know of:
char[] myCharArray = myStringArray.toCharArray();
But obviously that doesn't work.
How would I do this?
Upvotes: 1
Views: 4565
Reputation: 44854
Assuming that a myStringArray is an array of Strings you would have to first iterate through this array extracting each individual String before converting the String to an array of chars.
for example
for (String str : myStringArray) {
{
char[] myCharArray = myStringArray.toCharArray();
// do something with myCharArray
}
Upvotes: 0
Reputation: 236140
Here's one way to grab all the chars from all the strings in a single char array, if that's what you meant with the question:
String[] strArray = {"ab", "cd", "ef"};
int count = 0;
for (String str : strArray) {
count += str.length();
}
char[] charArray = new char[count];
int i = 0;
for (String str : strArray) {
for (char c : str.toCharArray()) {
charArray[i++] = c;
}
}
System.out.println(Arrays.toString(charArray));
=> [a, b, c, d, e, f]
Upvotes: 1
Reputation: 3185
You need to use a 2d/jagged array.
char[][] char2dArray = new char[myStringArray.length()][];
for ( int i=0; i < myStringArray.length(); i++) {
char2dArray[i] = myStringArray[i].toCharArray();
}
Upvotes: 2
Reputation: 467
You need to iterate through your String array converting every string in the string array to a char and then add that new char to your char array.
Upvotes: 0