Search code examples
javamultidimensional-arraytype-conversionchar

Java: Convert a 2d Array of String in a 1d Array of char


how can I convert a 2d Array of String: String[][] = {{"A", "-.-"},{"B", "..-"}} into a array of char: char[] c = {"A","B"}?

Can somebody help me?


Solution

  • You have an input and you create an output of the same .length as the input's .length, then loop an i index through the range of 0 ...length - 1 and get the i'th record's 0'th record (the letter) and get its first char via charAt(0).

    String[][] input = new String[][] {{"A", "-.-"},{"B", "..-"}};
    char[] output = new char[input.length];
    for (int i = 0; i < input.length; i++) {
        output[i] = input[i][0].charAt(0);
    }