java - 如何将字符串放入矩阵?

标签 java arrays string matrix words

我遇到了麻烦,也许你可以帮助我: 我有 3 个字符串,例如:word1、word2、word3,我必须用它们构建一个矩阵,如下所示: 第一行:word1("ABC"),第二行:word2("DEF"),第三行:word3("GHI")。

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

我需要这个,因为之后我必须检查形成的单词(“ADG”,“BEH”,“CFI”)是否在单词数组中。我不知道如何将这些字符串放入矩阵中,以便我可以检查。任何帮助都是有用的。 谢谢

最佳答案

基于此评论:

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.

为了使这项工作顺利进行,我将假设一些事情(因为我们没有足够的信息):

  1. 您有一个 String 数组,其中包含所有单词

    private String[] words;
    
  2. 您有一个方法可以从此数组中随机选取 3 个String

    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...
    }
    

因此,您需要一个基于这 3 个 Stringchar 数组。这段代码可以为您完成这项工作:

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

当然,如果您想让此方法支持超过 3 个 String,您可以使该方法接收随机数量的 String:

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

关于java - 如何将字符串放入矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16121388/

相关文章:

python - 将字节转换为字符串

java - 在 TextArea Java 中移动文本光标

java - 反向打印数组中的值

c - 如何将句子扫描到字符串数组中?

objective-c - 我可以做一个简单的初始化字符串格式使用@"

MySQL:在 "WHERE <column_name> IN <values>"查询中使用字符串

java - 处理 HTML POST 上的自定义变量

java - 保存和构建分块图像的最有效的内存方式是什么?

java - 在 UI 线程之外修改 FXCollections.synchronizedObservableList

C++ std::generate 函数总是给出相同的值