将字符串附加到2d Array Java中

时间:2018-02-13 22:08:14

标签: java

我有一个包含以下内容的字符串:

String text = "abcdefghijkl"

我想把它放在一个2d数组中,这样就会有4行3

这是我目前所拥有的,但其工作不正常:

char boxChar[][] = new char[4][3];
        int j,i;

        for (i = 0; i<4; i++)
        {
            for (j=0; j<3; j++)
            {            

                boxChar[i][j] = text.charAt((i+1)*(j));

            }

        }

        return boxChar[row][col];

2 个答案:

答案 0 :(得分:2)

看起来你的索引混乱了。我在原始代码中添加了一些打印语句,并进行了修改,以便在charAt指令中获得正确的字符。

    String text = "abcdefghijkl";

    char boxChar[][] = new char[4][3];
    int j,i;

    for (i = 0; i<4; i++)
    {
        for (j=0; j<3; j++)
        {            

            boxChar[i][j] = text.charAt(i*3+j);
            System.out.print(boxChar[i][j]);
        }
        System.out.println();

    }

如果它没有按照您的预期排列,有时将它记录在一张纸上可能会有所帮助。

使用输入字符串,1d数组上的位置为

a    b    c    d    e    f    g    h    i    j    k    l
0    1    2    3    4    5    6    7    8    9   10   11

当您循环获取框数组(矩阵)时,外部循环表示您需要四行三列,换句话说

a    b    c
d    e    f
g    h    i
j    k    l

因此对于第一个元素a,其位置为(0,0)b位于(0,1),依此类推。您的charAt(position)必须将2d位置映射到相应的1d位置。

答案 1 :(得分:2)

错误的索引,否则你很好:

String text = "abcdefghijkl";
int rows = 4;
int cols = 3;
char boxChar[][] = new char[rows][cols];

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {            
        boxChar[i][j] = text.charAt((i * cols) + j);
    }
}

//return boxChar[row][col];

System.out.println(boxChar[0]);
System.out.println(boxChar[1]);
System.out.println(boxChar[2]);
System.out.println(boxChar[3]);