Modify You
Modify You

Reputation: 153

Convert String array to Char array

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

Answers (4)

Scary Wombat
Scary Wombat

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

Óscar López
Óscar López

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

JustinDanielson
JustinDanielson

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

justin henricks
justin henricks

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

Related Questions