将1D String数组转换为2D String数组

时间:2021-09-28 21:58:38

I have this String array:

我有这个String数组:

String[] spltstr = {"a","b","c","d","e","f",...,"z"};

And I need to place every value there into an array like this:

我需要将每个值放在一个这样的数组中:

String[][] matrix;

I know the dimensions of both arrays, and as an output I need my matrix to look like:

我知道两个数组的尺寸,作为输出我需要我的矩阵看起来像:

matrix={{"a","b","c","d","e","f"},
        {"g","h","k","l","m","n"},
        {...................."z"}};

Can you tell me if this is possible? I'm having problems since the dimension of the first array is "n" and the second array is an "m"x5.

你能告诉我这是否可行?我有问题,因为第一个数组的维度是“n”,第二个数组是“m”x5。

If you think there is a better way to get this done I would be thankful.

如果您认为有更好的方法来完成这项工作,我将非常感激。

2 个解决方案

#1


2  

It is possible.

有可能的。

Think about the mapping.

想想映射。

n  (i,j)
0->(0,0)
1->(0,1)
2->(0,2)
3->(0,3)
4->(0,4)
5->(1,0)
6->(1,1)
7->(1,2)

etc...

So the idea is to transform n into a pair of (i,j)

所以想法是将n转换成一对(i,j)

#2


0  

well, if you know the sizes of the array, you can write a while loop to populate matrix.

好吧,如果你知道数组的大小,你可以写一个while循环来填充矩阵。

Have 3 variables outside the loop called Row, and Col, and Out. You know that there are X letters per row. So you check in your while loop if you have populated the (X-1)th index of matrix, you update row to row++, and col to 0. Each iteration of the loop, you'll do Col++, as well as Out++.

循环外有3个变量,分别为Row,Col和Out。你知道每行有X个字母。所以你检查你的while循环,如果你已经填充了矩阵的第(X-1)个索引,你将行更新为行++,并将col更新为0.循环的每次迭代,你将做Col ++,以及Out ++。

Because Row and Col and Out are being updated, you can just set matrix[Row][Col] to equal spltstr[Out].

由于Row和Col和Out正在更新,您只需将矩阵[Row] [Col]设置为等于spltstr [Out]即可。

You'll finish the problem once you run out of letters in the alphabet.

一旦字母表中的字母用完,你就会完成问题。

#1


2  

It is possible.

有可能的。

Think about the mapping.

想想映射。

n  (i,j)
0->(0,0)
1->(0,1)
2->(0,2)
3->(0,3)
4->(0,4)
5->(1,0)
6->(1,1)
7->(1,2)

etc...

So the idea is to transform n into a pair of (i,j)

所以想法是将n转换成一对(i,j)

#2


0  

well, if you know the sizes of the array, you can write a while loop to populate matrix.

好吧,如果你知道数组的大小,你可以写一个while循环来填充矩阵。

Have 3 variables outside the loop called Row, and Col, and Out. You know that there are X letters per row. So you check in your while loop if you have populated the (X-1)th index of matrix, you update row to row++, and col to 0. Each iteration of the loop, you'll do Col++, as well as Out++.

循环外有3个变量,分别为Row,Col和Out。你知道每行有X个字母。所以你检查你的while循环,如果你已经填充了矩阵的第(X-1)个索引,你将行更新为行++,并将col更新为0.循环的每次迭代,你将做Col ++,以及Out ++。

Because Row and Col and Out are being updated, you can just set matrix[Row][Col] to equal spltstr[Out].

由于Row和Col和Out正在更新,您只需将矩阵[Row] [Col]设置为等于spltstr [Out]即可。

You'll finish the problem once you run out of letters in the alphabet.

一旦字母表中的字母用完,你就会完成问题。