That's one way
public String everyNth(String s, int n) {
if (s.length() >= n) {
return s.charAt(n - 1) + everyNth(s.substring(n), n);
} else {
return "";
}
}
You could formulate a tail recursive version that doesn't need to do anything with returned results. Some languages like Scala can use this for optimization that avoids limited stack depth (and StackOverflow-exceptions), but not java, as for now.
public String everyNthAcc(String s, String acc, int n) {
if (s.length() >= n) {
return everyNthAcc(s.substring(n), acc + s.charAt(n - 1), n);
} else {
return acc;
}
}
@Test
public void tryIt() {
assertEquals("cccc", everyNthAcc("abcabcabcabc","", 3));
}
So as it is for now, the smaller the size of each stack frame, the deeper you can get with the recursion, that should make it further, its a bit weird, though:
public class EveryNth {
String value = "abcabcabcabc";
StringBuilder sb = new StringBuilder();
int nth = 3;
@Test
public void tryIt() {
everyNthAgain(nth);
assertEquals("cccc", sb.toString());
}
public void everyNthAgain(int curr) {
if (curr <= value.length()) {
sb.append(value.charAt(curr - 1));
everyNthAgain(curr + nth);
}
}
}