java - getting a certain number of characters from a 2D char array -


i have 2d char array , want print first 3 characters of every 5 characters in each nested array. doing:

char [][] 1 ={ {'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]; (int i=0; i< one.length;i++){     (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("");  } 

this gives following output:

abc ijk qrs 

i want output:

abc fgh ijk nop qrs vwx 

this work dynamically, work longer input lengths.

note third nested loop not necessary, , need iterate through each nested array, using count variable keep track of in regards adding first 3 of each 5 characters.

note used arraylist<string>, keep track of three-character sequences should printed, that's not necessary, print directly in (count == 3) case.

import java.util.arraylist;  public class printthreeoffive {   public static void main(string[] args)   {      char [][] 1 ={ {'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];      (int i=0; i< one.length;i++){          int count = 0;          (int j=0; j < one[i].length; j++){             //re-set count @ 5th character            if (count == 4){               count = 0;              continue; //continue fifth character not added            }             //if in first 3 of five, add firstthree            if (count < 3){              firstthree[count]=one[i][j];            }             //increment count, , add list if @ third character            count++;            if (count == 3){              output.add(new string(firstthree));            }           }      }      (string s : output){         system.out.println(s);     }   } } 

output:

abc fgh ijk nop qrs vwx 

Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -