我正在编写自己的函数,该函数将检查第二个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;
}
我的问题是,第二个字符串中的前三个字符与第一个字符串中的前三个字符相同。第四个字符不同。现在,我想从s1返回第三个字符,并从s2
的第一个字符开始从这里开始,但是我陷入了循环。
答案 0 :(得分:2)
尝试一下(必要的注释在代码中):
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;
}