0

I'm working on a short project to search a string for a specified substring using recursion.

I have tried using various strings and substrings, as well as making my code as simple as possible, but it always returns false if the substring is more than one character. (I have an accessor and mutator, as well as int i set to 0 before this method)

public boolean find(String target) {
    if (i == target.length()) {
        return true;
    }
    System.out.println(sentence);
    if (sentence.length() < target.length()) {
        return false;
    }
    if (getSentence().toLowerCase().charAt(0) == target.toLowerCase().charAt(0)) {
        i++;
    } else {
        i = 0;
    }
    sentence = sentence.substring(1);
    return find(target);
}

Tester code and output:

public static void main(String[] args) {
    Sentence test = new Sentence("Lizard");
    System.out.println(test.find("z"));

    Sentence test2 = new Sentence("Seventeen");
    System.out.println(test2.find("teen"));     
}
Lizard 
izard 
zard 
true 

Seventeen 
eventeen 
venteen 
enteen 
nteen 
teen 
een 
false
2
  • So...where's i defined? Commented Apr 17, 2019 at 21:36
  • You are comparing character-by-character, but as soon as the sentence.length() < target.length() you return false so your code can't continue checking the remaining characters Commented Apr 17, 2019 at 21:36

1 Answer 1

2

Your method only tests target at the first character, but you modify the sentence - e.g. you also need to modify your target when you recurse. Something like,

public boolean find(String target) {
    if (i == target.length()) {
        return true;
    }
    System.out.println(sentence);
    if (sentence.length() < target.length()) {
        return false;
    }
    if (sentence.toLowerCase().charAt(0) == target.toLowerCase().charAt(0)) {
        i++;
    } else {
        i = 0;
    }
    sentence = sentence.substring(1);
    return find(target.substring(1));
}
Sign up to request clarification or add additional context in comments.

1 Comment

That solved my problem and worked for the examples I gave, however I want it to work with sentences too. I modified it to work when the first matching character is not in the beginning of the string by moving the target.substring to right beneath the i++ line, and adding a line after i = 0 that restores the substring to the original target.

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.