I want to skip every 3rd string element from loop java?

I don't know which condition I should add. I've tried everything. I have one string which I have created array based on split function. So I want to remove every 3rd element.

 String test = "Peter Pi,93,99999,Thoby Ty,22,999999,Philip Mili,48,999999" 
  String array1[]=.split(",");
    String data = "";
    for(int i=0;i<array1.length;i++){
      if (i % 6 > 2) {
          System.out.println(array1[i]);      
      }
    }

Result I want accomplish:Peter Pi93Thoby Ty22Philip Mili48

Thanks in advance

1 answer

  • answered 2020-03-25 13:38 Fildor

    I'd actually skip every 3rd item:

    for(int i=0;i<array1.length;i++){
          if (i+1 % 3 == 0) {
             continue;
          }
          System.out.println(array1[i]);    // 0,1,3,4,6,7,...
    }
    

    Alternative with less iterations:

    for ( int i=0; i < array.length/3; i++){
        System.out.println(array1[i*3]);     // 0, 3, 6,  9, ...
        System.out.println(array1[i*3+1]);   // 1, 4, 7, 10, ...
    }