如何在c#中编写自己的字符串包含函数

How to write an own string contains function in c#

我正在编写自己的函数,它检查第二个 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;
}