将char数组列存储到字符串中以进行比较

时间:2013-05-16 01:24:04

标签: java char equality

我有一个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 跳闸

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

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

只应在循环结束时打印。

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

目前匹配

a
av
avx
avxc

但是,因为你将它们全部打印在一行上就可以了

aavavxavxc

答案 1 :(得分: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);

 }

答案 2 :(得分: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
            }
        }
    }

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