jdk
jdk

Reputation: 1

Search a string for a specified substring using recursion

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

Upvotes: 0

Views: 78

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201419

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

Upvotes: 2

Related Questions