Home > Back-end >  Need help trying to figure out recursion with String
Need help trying to figure out recursion with String

Time:09-12

I am new to Java and I am trying to figure out how to count two characters in a string as one and still count the other characters on top of that using recursion, but I have been sitting here for a while and still can't seem to figure this out. It will only print each time ch appears in a string, but not other characters. For example, when I type geugeu, I need it to print that the count is 4, but it only prints it as 2.

public static int recursionCount(String str) {
    if(str.length() == 1) {
        return 0;   
    }
    else {
        String ch = str.substring(0, 2);
        if(ch.equals("eu") {
            return 1   recursionCount(str.substring(1));
        }
        else {
            return recursionCount(str.substring(1));
        }
    }
}

CodePudding user response:

OP wants to count all characters in a string but adjacent characters "ae", "oe", "ue", and "eu" should be considered a single character and counted only once.

Below code does that:

public static int recursionCount(String str) {
    int n;
    n = str.length();
    if(n <= 1) {
        return n; // return 1 if one character left or 0 if empty string.
    }
    else {
        String ch = str.substring(0, 2);
        if(ch.equals("ae") || ch.equals("oe") || ch.equals("ue") || ch.equals("eu")) {
            // consider as one character and skip next character
            return 1   recursionCount(str.substring(2));
        }
        else {
            // don't skip next character
            return 1   recursionCount(str.substring(1));
        }
    }
}
  •  Tags:  
  • java
  • Related