1

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();
        }
    }
}
1
  • 6
    I hope you understand, that "it doesn't work" is not a helpful description about your problem with that code. Commented Jan 18, 2015 at 14:33

1 Answer 1

4

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]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.