简体   繁体   中英

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?

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

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]

您需要遍历String数组,将字符串数组中的每个字符串转换为char,然后将该新char添加到char数组中。

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 
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM