Skip to content
Advertisement

Count the Characters in a String Recursively & treat “eu” as a Single Character

I am new to Java, and I’m trying to figure out how to count Characters in the given string and threat a combination of two characters "eu" as a single character, and still count all other characters as one character.

And I want to do that using recursion.

Consider the following example.

Input:

"geugeu"

Desired output:

4   // g + eu + g + eu = 4

Current output:

2

I’ve been trying a lot and still can’t seem to figure out how to implement it correctly.

My code:

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));
        }
    }
}

Advertisement

Answer

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));
        }
    }
}
6 People found this is helpful
Advertisement