How to convert a String array to char array in Java

前端 未结 6 1698
孤城傲影
孤城傲影 2020-12-10 00:33

We are given an array of Strings and what we require is a char[], i.e, array of all characters in all the Strings For example:

Input: [i, love, you]

output:

6条回答
  •  轮回少年
    2020-12-10 00:49

    You can do that like this

    char[] allchar = new char[total]; // Your code till here is proper
    
    // Copying the contents of the 2d array to a new 1d array
    int counter = 0; // Counter as the index of your allChar array
    for (int i = 0; i < a1.length; i++) { 
        for (int j = 0; j < a1[i].length; j++) { // nested for loop - typical 2d array format
            allchar[counter++] = a1[i][j]; // copying it to the new array
        }
    }
    

提交回复
热议问题