Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

everyNthExcept(String string, int start, int skip, int except) returns a String

ID: 3726063 • Letter: E

Question

everyNthExcept(String string, int start, int skip, int except) returns a String
Returns every skipth character of string, starting with the start-th character, except do not include the character if it is one of the except-th characters from start. For example: everyNthExcept(s, 2, 2, 4)should include every 2nd character of s, starting with the second character of s, but it does not include every 4th character after the second character of s. You can assume start, skip, and except are all positive.
everyNthExcept("abcdefghijklmnop", 2, 2, 4) should return "bdhlp"
everyNthExcept("abcdefghijklmnop", 3, 2, 4) should return "ceim"

You are allowed to use the following from the Java API:

class String

length

charAt

class StringBuilder

length

charAt

append

toString

class Character

any method

Explanation / Answer

package learning;

public class EveryNthExcept {

public static void main(String args[]){
  System.out.println(everyNthExcept("abcdefghijklmnop", 2, 2, 4));
  System.out.println(everyNthExcept("abcdefghijklmnop", 3, 2, 4));
}

public static String everyNthExcept(String string, int start, int skip, int except ){
  int nextExcept = except; // to look for next character to except
  StringBuilder sb = new StringBuilder(); // Use string builder so that we can append characters
  for(int i= start-1; i<string.length(); i = i+skip){ // run through length of the string by jumping "skip" characters
   if(i == start + nextExcept -1){ // don't include every except character after start index
    nextExcept = nextExcept + except;
   } else {
    char c = string.charAt(i);
    sb.append(c);
   }
  }
  return sb.toString();
}

}