1

I have java class that will call recursive method for string replace. The method will return the string after replacing all required character one by one. But this not working as expected. Please find the code below.

public class TestingRecursion {
    private static String startRecursion(String value){
        value = value.replaceFirst("a", "b");
        if(value.contains("a"))
            startRecursion(value);
        return value;   
    }

    public static void main(String[] args) {
        String value = "1a 2a 3a 4a";

        String afterRecursion = startRecursion(value);
        System.out.println(afterRecursion);
    }
}

Expected output - "1b 2b 3b 4b" Actual output - "1b 2a 3a 4a".

2 Answers 2

5

You're not using the return value from startRecursion.

Line 5 should be:

    value = startRecursion(value);
Sign up to request clarification or add additional context in comments.

Comments

4

With the existing linear recursion logic, what you have missed is -

if(value.contains("a"))
    return startRecursion(value);

It will return the value back.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.