简体   繁体   中英

Convert a string array to char array

Im trying to convert a string array to char array.

Eg

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

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]]

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