naa
naa

Reputation: 21

How to recursively remove a character from a string?

How do I remove a target character from string using RECURSION?

I know it begins like:

public static String removeChar(String str, char target) {
    if (str.length() == 0) {
        return str;
    } else {
        if (str.charAt(0) == target) {
            return removeChar(/*what goes in here?*/)
        }
        return removeChar(/*what goes in here?*/)
    }
}

thank you!!

Upvotes: 2

Views: 7695

Answers (4)

I suggest this solution.

function isLetter(str) {
    return str.length === 1 && str.match(/[A-Z]/i);
}

function removeLetters(str) {
    //console.log(str);
    let val = str.substr(0, 1);
    console.log(val);
    if (isLetter(val)) {
        return removeLetters(str.substr(1))
    } else {
        console.log("Return", str);
        return str;
    }
}  

Upvotes: 0

forpas
forpas

Reputation: 164089

You check the index of the 1st occurrence of the char and remove it from that position:

public static String removeChar(String str, char target) {
    int index = str.indexOf(target);
    if (index < 0)
        return str;
    else {
        return removeChar(str.substring(0, index) + str.substring(index + 1), target);
    }
}

public static void main(String[] args) {
    String str = "0123045607890";
    System.out.println(removeChar(str, '0'));
} 

will print:

123456789

Upvotes: 0

jenald
jenald

Reputation: 182

You could use the following code inside the else-block:

if(str.charAt(0) == target) {
    return removeChar(str.substring(1), target);
}
return charAt(0) + removeChar(str.substring(1), target);

But I don't see a need to use recursion here, you could just use

str.replace(target, '');

Upvotes: 0

Eran
Eran

Reputation: 393781

The idea is that if the first character is equal to the target character, you simply return the result of removeChar() applied on the rest of the String (i.e. the String without the first character), which removes the first character.

On the other hand, if the first character is not equal to the target character, you return a String starting with the original first character and ending with the result of applying removeChar() on the rest of the String.

public static String removeChar(String str, char target) {
    if(str.length() == 0) {
        return str;
    } else {
        if(str.charAt(0) == target) {
            // remote the first character, and apply the recursive method to
            // the rest of the String
            return removeChar(str.substring(1),target);
        } else {
            // don't remote the first character, and apply the recursive method to
            // the rest of the String
            return str.charAt(0) + removeChar(str.substring(1),target);
        }
    }
}

Upvotes: 2

Related Questions