# 如何将字符串放入矩阵？ (How to put strings into a matrix?)

### 问题

``````A|B|C
D|E|F
G|H|I
``````

### 解决方法

1. 你有一个`String`包含所有单词的数组

``````private String[] words;
``````
2. 你有一个`String`从这个数组中随机选取3 秒的方法。

``````private String s1, s2, s3;

public void pickThreeRandomWords() {
s1 = aRandomWord(words);
s2 = aRandomWord(words);
s3 = aRandomWord(words);
//or maybe another fancy algorithm to get this...
}
``````

``````public char[][] createMatrixFromStrings(String s1, String s2, String s3) {
char[][] theMatrix = new char[]; //yes, hardcoded
theMatrix = s1.toCharArray();
theMatrix = s2.toCharArray();
theMatrix = s3.toCharArray();
return theMatrix;
}
``````

``````public char[][] createMatrixFromStrings(String ... strings) {
if (strings == null || strings.length == 0) return null;
char[][] theMatrix = new char[strings.length][];
int i = 0;
for(String s : strings) {
theMatrix[i++] = s.toCharArray();
}
return theMatrix;
}
``````

### 问题

I'm having trouble with this, maybe you could help me: I have 3 strings like: word1, word2, word3 and I have to build a matrix with them, like this: on the first row : word1("ABC"), second row: word2("DEF") and third row: word3("GHI").

``````A|B|C
D|E|F
G|H|I
``````

I need this because after that I have to check if the formed words ("ADG","BEH","CFI") are in an array of words. And I don't know how to put those strings in the matrix so I can check. Any help is useful. Thanks

### 解决方法

Based on this comment:

the words have the same size, because the matrix is actually like a puzzle. I choose randomly 3 words from an array, put them in a matrix and check after that if the words resulted are from the same array.

I'll assume some things in order to make this work (since we don't have enough info):

1. You have an array of `String`s where you have all the words

``````private String[] words;
``````
2. You have a method to randomly pick up 3 `String`s from this array.

``````private String s1, s2, s3;

public void pickThreeRandomWords() {
s1 = aRandomWord(words);
s2 = aRandomWord(words);
s3 = aRandomWord(words);
//or maybe another fancy algorithm to get this...
}
``````

So you would need an array of array of `char`s based on these 3 `String`s. This code could do the work for you:

``````public char[][] createMatrixFromStrings(String s1, String s2, String s3) {
char[][] theMatrix = new char[]; //yes, hardcoded
theMatrix = s1.toCharArray();
theMatrix = s2.toCharArray();
theMatrix = s3.toCharArray();
return theMatrix;
}
``````

Of course, if you would want to make this method to support more than 3 `String`s you can make the method to receive a random quantity of `String`s:

``````public char[][] createMatrixFromStrings(String ... strings) {
if (strings == null || strings.length == 0) return null;
char[][] theMatrix = new char[strings.length][];
int i = 0;
for(String s : strings) {
theMatrix[i++] = s.toCharArray();
}
return theMatrix;
}
``````