我正在编写自己的函数,它检查第二个string
是否包含在第一个string
中。我知道这种方法已经实现,但我找不到它的源代码,我需要它来考试。
private static bool Contains(String s1, String s2) { //s1 = bababi, s2= babi
int correctCharCount = 0;
for(int i = 0, j = 0; i < s1.Length; i++) {
if (s1[i] == s2[j]) {
correctCharCount++;
j++;
} else {
correctCharCount = 0;
j = 0;
i--;
}
}
Console.WriteLine("count: " + correctCharCount);
Console.WriteLine("s2 length: " + s2.Length);
if (correctCharCount == s2.Length) return true;
else return false;
}
我的问题是,第二个字符串中的前三个字符与第一个字符串中的前三个字符相同。第 4 个字符不同。现在我想回到 s1 的第 3 个字符,然后从这里再次从这里开始,从 s2
中的第一个字符开始,但我陷入了一个循环。
试试这个(必要的注释在代码中):
public static bool Contains(string stringToSearch, string stringToFind)
{
var maxIndex = stringToSearch.Length - stringToFind.Length;
// String, which we want to find is bigger than string, which we want to search
if (maxIndex < 0) return false;
for (int i = 0; i <= maxIndex; i++)
{
int j;
for (j = 0; j < stringToFind.Length; j++)
// If we have different letters, stop comparing and go to next iteration of outer loop
if (stringToSearch[i + j] != stringToFind[j]) break;
// If we reached last iteration of a loop then we found the string
if (j == stringToFind.Length) return true;
}
// If we reached this point, we didn't find the string
return false;
}