0

Task

Given a string, return a string made of the chars at indexes 0,1, 4,5, 8,9 ... so "kittens" yields "kien".

Example test-cases:

altPairs("kitten") → "kien"
altPairs("Chocolate") → "Chole"
altPairs("CodingHorror") → "Congrr"

Solution (to be explained)

   String result = "";
  
  /* I understand that I am running 
  i by 4 to hit 0, 4, 8,12 and all 
  following ints until the string length ends.*/
  for (int i=0; i<str.length(); i += 
    4) {
    /* why is using   
    i + 2 is the best way to solve.      
    this. How is it applicable when    
    i+1 seems to be 1, 
    5, 9, 13 etc.*/
    int end = i + 2;
    if (end > str.length()) {
      end = str.length();
    }
    result = result + 
    str.substring(i, end);
    }
  
  return result;
   }
hc_dev
  • 8,389
  • 1
  • 26
  • 38
  • _why is using i + 2 is the best way to solve._ Because the 2nd parameter to `substring` is exclusive. So, for example, when `i = 0` and `end = 2` you call `substring(0, 2)` which returns values at indexes `0` to `1`. (Of course "best" is subjective...) – 001 Jul 01 '21 at 18:07
  • Your title (question) is a bit vague. Can you rephrase the concrete question in "prose" (human language) in the post. For example, would you like to explain (a) in code or to a human (b) as programming task ? And more important, what did you try as _explanation_, can you provide an example, please. – hc_dev Jul 01 '21 at 18:38

1 Answers1

1

You are complicating it. It can be as simple as:

StringBuilder sb = new StringBuilder();

String str = "CodingHorror";
for (int i = 0; i < str.length(); i += 4) {
  sb.append(str.charAt(i));
  if (i + 1 < str.length()) {
    sb.append(str.charAt(i + 1));
  }
}

System.out.print(sb.toString());    // Congrr

Always use a StringBuilder when manipulating Strings inside a loop. StringBuilder vs String concatenation in toString() in Java

Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43