2013-05-16 267 views
2

我有一個字符數組[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 行程

任何幫助將不勝感激。

回答

0

問題在於你在循環的每次迭代中打印匹配。

只應在循環結束時打印。

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

目前的比賽是

a 
av 
avx 
avxc 

但既然你把它們打印全部在一行上你

aavavxavxc 
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); 

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

您可以享受創造一些除了你的正則表達式的正則表達式。