Sasino
Sasino

Reputation: 69

Convert a string array to char array

Im trying to convert a string array to char array.

E.g.

Str[0] = "string1"

Str[1] = "string2"

to

Char[0][0] = 's'  Char[0][1] = 't'  Char[0][2] = 'r'   .. Char[0][6] = '1' 

Char[1][0] = 's'  Char[1][1] = 't'  Char[1][2] = 'r'   .. Char[1][6] = '2' 

..etc

Here is what I've got so far. But it doesnt work and I need you guys help.

public class Char {
    public void toChar(String[] str)
    {
        char[][] charArray = new char[str.length][100];

        for(int i=0;i<str.length;i++)
        {
            charArray[i][] = str[i].toCharArray();
        }
    }
}

Upvotes: 1

Views: 2603

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201527

Remove the empty bracket, like

charArray[i] = str[i].toCharArray();

Also, your declaration of the charArray may omit the second dimension like

char[][] charArray = new char[str.length][];

Finally, your method is void; to use your charArray you must return it. Since it doesn't depend on any instance state, it might be static. Putting it all together, it might look like

public static char[][] toChar(String[] str) {
    char[][] charArray = new char[str.length][];

    for (int i = 0; i < str.length; i++) {
        charArray[i] = str[i].toCharArray();
    }
    return charArray;
}

and then you could call it like

public static void main(String[] args) throws Exception {
    System.out.println(Arrays.deepToString(toChar(new String[] { "Hello",
            "World" })));
}

Output is

[[H, e, l, l, o], [W, o, r, l, d]]

Upvotes: 4

Related Questions