简体   繁体   English

递归检查一个字符串是否等于另一个字符串

[英]Recursion to check if a String equals another string

my current code returns the output: 我当前的代码返回输出:

true
Expected: true

false
Expected: true

false
Expected: true

false
Expected: false

false
Expected: false 

So there's an issue with my logic that i'm not seeing 所以我的逻辑有一个问题,我没看到

public static void main(String[] args)
{

    System.out.println(find("",""));
    System.out.println("Expected: true\n");

    System.out.println(find("Mitten","Mit"));
    System.out.println("Expected: true\n");
    System.out.println(find("I love my CS courses!"," CS"));
    System.out.println("Expected: true\n");
    System.out.println(find("","Cookies."));
    System.out.println("Expected: false\n");
    System.out.println(find("Java","Python"));
    System.out.println("Expected: false\n");


}
public static boolean find(String text, String str)
{

    boolean found = false;
    if(text.length() == 0 && str.length() == 0)
    {
        found = true;
        return found; 
    }
    if(text.length() == 0 || str.length() == 0)
    {
        return found; 
    }
    if(str.length() > text.length())
    {
        return found;
    }
    if(str.equals(text.substring(0,str.length()-1))) 
    {
        found = true;   
    }
    else
    {
        text = text.substring(1);
        find(text, str);
    }
    return found;
}

please help 请帮忙

I see an issue with this statement 我发现此声明有问题

if(str.equals(text.substring(0,str.length()-1))) 

Since the second index of substring is exclusive, it should be 由于substring的第二个索引是互斥的,因此它应该是

if(str.equals(text.substring(0,str.length()))) 

in order to compare str to the first str.length characters of text . 为了比较strtext的前str.length字符。

Of course you can use text.contains(str) or text.startsWith(str) and eliminate some of your code, but perhaps that's not part of the exercise requirements. 当然,您可以使用text.contains(str)text.startsWith(str)并删除一些代码,但这也许不是练习要求的一部分。

Beside that issue, when you make a recursive call, you should usually do something with the value returned by that call : 除了这个问题,当您进行递归调用时,通常应该使用该调用返回的值来做一些事情:

found = find(text, str);

otherwise, why make the recursive call in the first place? 否则,为什么要首先进行递归调用? (unless it has side effects of mutating the objects passed as parameters to the recursive call, which it does not in your case) (除非它具有使作为参数传递给递归调用的对象发生变化的副作用,但您的情况不会这样做)

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

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