Use recursive method to prints a string with every second character removed

MissyDev :

I want to remove every second character from a string using the recursive method.

    public static void main(String[] args) {
        System.out.println(everySecond("wonderful"));

    }
    public static String everySecond(String s) {

        if (s.length() % 2 != 0 ) {
            System.out.print(s.substring(0,1));
        }
        if (s.length() <= 1) {
            return s;
        }
        else {
                String simpler = everySecond(s.substring(1))+ s.charAt(0);
                return "";
        }
    }
}

Currently the program does what I need. However, I want to include everything in the sub-recursive call String simpler = everySecond(s.substring(1))+ s.charAt(0); return ""; and remove code below.

if (s.length() % 2 != 0 ) {
            System.out.print(s.substring(0,1));
        }

I am fairly new to Java so I apologize if the answer is obvious. I assume I am overlooking some very basic solution here.

djharten :

If the remaining length of the String is < 2 then we don't need to find any more characters to skip over. Otherwise, we need the initial character and then the rest of the String after the second character(the skipped one), therefore I did it like this:

  public static String removeEverySecondChar(String str) {
    if(str.length() < 2) {
      return str;
    }
    return str.substring(0,1) + removeEverySecondChar(str.substring(2));
  }

Input: Wonderful

Output: Wnefl

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=417544&siteId=1