带有 startsWith 方法和子字符串的输出不清楚



我在理解这段代码时遇到问题。让我感到困惑的部分是输出,尤其是 3 和 5 打印状态。第三个怎么可能是真的,第五个是假的。我理解子字符串的方式是它与索引后面的值"操作"。因此,这里它仍然打印出 true 对于 "This",尽管它应该是索引 0,而对于 "文本" 为 false。为什么会这样?

public class test {
private static final String TEXT = "This is the text to be searched";
private static boolean hasSubstring(String toFind, String findFrom) {
if (findFrom.length() == 0) {
return false;
}
if (findFrom.startsWith(toFind)) {
return true;
}
return hasSubstring(toFind, findFrom.substring(1));
}

public static void main(String[] argv) {
System.out.println(hasSubstring("text to", TEXT));
System.out.println(hasSubstring("goo", TEXT));
System.out.println(hasSubstring("This", TEXT));
System.out.println(hasSubstring("searched", TEXT));
System.out.println(hasSubstring("the  text", TEXT));
}
}

来自 Oracle defn,

字符串 - 子字符串

public String substring​(int beginIndex)

返回一个字符串,该字符串是此字符串的子字符串。子字符串以指定索引处的字符开头,并延伸到此字符串的末尾。 例子:

"unhappy".substring(2( 返回 "happy">

"Harbison".substring(3( 返回 "bison">

"空".子字符串(9( 返回 " (一个空字符串(

参数: beginIndex - 起始索引,包括。

返回: 指定的子字符串。

抛出: IndexOutOfBoundsException - 如果 beginIndex 为负数或大于此 String 对象的长度。

链接: https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#substring

因此,第 3 部分如预期的那样为真

第5 个测试文本中有双倍空格

System.out.println( hasSubstring ("the  text", TEXT ));

如上所述将其更新为单个空格,它将按预期正常工作。

System.out.println( hasSubstring ("the text", TEXT ));

以下是我更新文本的输出:

true
false
true
true
true

最新更新