2

我有一个单个字符的 char 数组 [4] [4],即。'a' 我试图只将数组的列存储到一个字符串中,以便与另一个字符串进行比较。但我遇到的问题是它不断将原始元素添加到字符串中。我下面的代码在数组中包含单词“car”和“trip”,并希望将其与带有这些单词的另一个字符串进行比较以使其成为真的。这是我的代码:

char[][] puzzle = {{'a', 'c', 'h' ,'t'}, 
                   {'v', 'a', 'x', 'r'}, 
                   {'x', 'r', 'e', 'i'}, 
                   {'c', 'q', 'i', 'p'}
                  };

for(int row=0; row<puzzle.length; row++)
{

  String match = "";
  String matchword ="";
  for(int col=0; col<puzzle.length; col++)
  {
   match += puzzle[col][row];
   System.out.print(match);
  }
 System.out.println();
}

到字符串的输出如下: aavavxavxc ccacarcarq hhxhxehxei ttrtritrip

而不是:avxc carq hxei trip

任何帮助将不胜感激。

4

3 回答 3

1

问题是您在循环的每次迭代中都打印匹配。

您应该只在循环完成时打印。

for(int col=0; col<puzzle.length; col++)
{
    match += puzzle[col][row];
}
System.out.println(match);

目前比赛是

a
av
avx
avxc

但是由于您将它们全部打印在一行上,因此您会得到

aavavxavxc
于 2013-05-16T01:27:46.623 回答
0

您可以使用基于您的数组的正则表达式puzzle[][]

        char[][] puzzle = {{'a', 'c', 'h' ,'t'}, 
            {'v', 'a', 'x', 'r'}, 
            {'x', 'r', 'e', 'i'}, 
            {'c', 'q', 'i', 'p'}
           };

    // regex array
    String[] regexs = new String[puzzle.length];

    int counter = 0;
    for(int row=0; row<puzzle.length; row++) {
        String match = "[";

        for (int col = 0; col < puzzle.length; col++) {
            match += puzzle[col][row];
            match += ",";
        }

        // Add regular expression into array
        regexs[counter] = match + "]";

        counter++;
    }

    // Prepare
    Pattern p = null;
    Matcher m = null;

    // Now parse with your inputs
    for(String arg : args) {

        for(String regex : regexs) {
            p = Pattern.compile(regex);
            m = p.matcher(arg);

            if(m.find()) {
                System.out.println(">>> OK. input: "+arg+" and matcher:"+regex);
            } else {
                // other output
            }
        }
    }

您可以享受为您的正则表达式添加一些内容。

于 2013-05-16T05:11:18.527 回答
0

试试这个,如果我理解你的要求是正确的。

    char[][] puzzle = {
                        {'a', 'c', 'h' ,'t'}, 
                       {'v', 'a', 'x', 'r'}, 
                       {'x', 'r', 'e', 'i'}, 
                       {'c', 'q', 'i', 'p'}
                      };

    String output = "";
    //we need to go throug the entire set of rows, but the tricky bit is in getting just say the first set of values [1][1], [2][1]... 
    //rather than getting the exterior as you were previously. 

    //Start by selecting element 1, 2, 3 from the outer array
    for(int i = 0; i < puzzle.length; i ++) {

        //Then perform the inner loop
        for(int j = 0; j < puzzle[i].length; j++) {
            output = output + puzzle[j][i]; //Here being the trick, select the inner loop first (j) and the inner second. Thus working your way through 'columns' 
        }

        output = output +"\n"; 
    }

    System.out.println(output);

 }
于 2013-05-16T01:50:04.000 回答