使用 Java 在字符串中查找子字符串

Finding substring in a string using Java

我在网上找到了这个答案,但我无法理解以下这些代码行在完整代码中的作用:

if (haystackLen - i + 1 < needleLen)
            return null;

在下面找到完整代码:

  public String strStr(String haystack, String needle) {

        int needleLen = needle.length();
        int haystackLen = haystack.length();

        if (needleLen == haystackLen && needleLen == 0)
            return "";

        if (needleLen == 0)
            return haystack;

        for (int i = 0; i < haystackLen; i++) {
            // make sure in boundary of needle
            if (haystackLen - i + 1 < needleLen)
                return null;

            int k = i;
            int j = 0;

            while (j < needleLen && k < haystackLen && needle.charAt(j) == haystack.charAt(k)) {
                j++;
                k++;
                if (j == needleLen)
                    return haystack.substring(i);
            }

        }

        return null;
    }
if (haystackLen - i + 1 < needleLen)
            return null;

因此您正在遍历 haystack 并检查其中的 needle。每次迭代

haystackLen - i + 1

给出大海捞针中 String 的长度,当它小于 needleLen 时,你打算找到你只是返回 null,因为你确定进一步的迭代是没有用的.

基本上您的代码正在检查第一个字符串中是否存在(准确)第二个字符串,然后您将返回第一个字符串。

如:

haystack="indian";
needle="india";

那么输出将是"indian"

如果

haystack="indian";
needle="indian";

那么输出将是 "indian".

如果

haystack="india";

needle="indian";

那么输出将是 "null"。

这是你的困惑。

 if (haystackLen - i + 1 < needleLen)
     return null;

如果第二个字符串长度大于第一个字符串并且第一个字符串匹配到第二个字符串中的当前索引,则返回空;这意味着第二个字符串不是第一个字符串的子字符串。