[英]Appending a string into 2d Array 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];
看来您混合了索引。 我在原始代码中添加了一些打印语句,并进行了修改,以便在charAt
指令中获得正确的char。
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();
}
有时,如果没有按照您的期望排列,将其记在一张纸上会很有帮助。
使用您的输入字符串,一维数组上的位置为
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位置。
只是错误的索引编制,否则您就很好:
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]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.