简体   繁体   English

使用递归在字符串中搜索指定的子字符串

[英]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. 我尝试使用各种字符串和子字符串,并使我的代码尽可能简单,但是如果子字符串超过一个字符,它将始终返回false。 (I have an accessor and mutator, as well as int i set to 0 before this method) (我有一个访问器和增幅器,以及在此方法之前将int i设置为0)

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

Your method only tests target at the first character, but you modify the sentence - eg you also need to modify your target when you recurse. 您的方法仅测试第一个字符处的target ,但您修改sentence -例如,递归时还需要修改target 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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM