2015-04-24 77 views
0

我有一個2D字符數組,我想打印每個嵌套數組中每五個字符的前三個字符。這是我在做什麼:從2D字符數組中獲取特定數量的字符

char [][] one ={ {'a','b','c','d','e','f','g','h','3'},{'i','j','k','l','m','n','o','p','7'},{'q','r','s','t','u','v','w','x','2'}}; 

int aSize=5; 
char [] firstThree=new char[3]; 
for (int i=0; i< one.length;i++){ 
    for (int j=0; j< aSize;j++){ 
     for(int m=0; m<3;m++){ 
      firstThree[m]=one[i][m]; 
     } 
    } 

    System.out.print(firstThree); 
    System.out.println(""); 
} 

此給出以下的輸出:

abc 
ijk 
qrs 

我想要的輸出:

abc 
fgh 
ijk 
nop 
qrs 
vwx 

回答

0

這會工作動態地做到這一點,所以將工作更長時間輸入的長度。

請注意,第三個嵌套循環不是必需的,您只需要遍歷每個嵌套數組,使用count變量來跟蹤您在哪裏添加每個五個字符的前三個。

請注意,我還使用了ArrayList<String>來跟蹤應該打印的三個字符的序列,但這並不是必須的,您可以直接在(count == 3)的情況下打印。

import java.util.ArrayList; 

public class PrintThreeOfFive 
{ 
    public static void main(String[] args) 
    { 
    char [][] one ={ {'a','b','c','d','e','f','g','h','3'},{'i','j','k','l','m','n','o','p','7'},{'q','r','s','t','u','v','w','x','2'}}; 

    int aSize=5; 
    ArrayList<String> output = new ArrayList<String>(); 
    char [] firstThree=new char[3]; 
    for (int i=0; i< one.length;i++){ 
     int count = 0; 
     for (int j=0; j < one[i].length; j++){ 

      //re-set count at the 5th character 
      if (count == 4){ 
      count = 0; 
      continue; //continue so that the fifth character is not added 
      } 

      //if in first three of five, add it to firstThree 
      if (count < 3){ 
      firstThree[count]=one[i][j]; 
      } 

      //increment count, and add to the list if at the third character 
      count++; 
      if (count == 3){ 
      output.add(new String(firstThree)); 
      } 

     } 
    } 

    for (String s : output){ 
     System.out.println(s); 
    } 
    } 
} 

輸出:

abc 
fgh 
ijk 
nop 
qrs 
vwx 
0

你可以這樣做:

for (int j=5; j < 8;j++){ 
    firstThree[j-5]=one[i][j]; 
} 

你不需要3個循環來做到這一點...

0

您可以創建另一個陣列讀取後5指標,如:

for(int m=0; m<3;m++){ 
    firstThree[m]=one[i][m]; 
    nextThree[m]=one[i+5][m]; 
} 
+0

這給了我一個索引越界異常。我明白你在說什麼,但是有沒有辦法動態地編碼呢?所以,如果我在一個數組中有未知數量的字符,並且我想從每5箇中獲得前3個字符。 – Smi28

0

我覺得@Masud是接近,但他的解決方案有一些運行時error.Change索引一點解決這個問題。

for(int m=0; m<3;m++){ 
    firstThree[m]=one[i][m]; 
    nextThree[m]=one[i][m+5]; 
} 

Demo