How to find substring from string without using indexof method in C#?

前端 未结 7 1420
时光取名叫无心
时光取名叫无心 2020-12-20 05:44

I want to find the position of a substring in a string if present without using any string method including indexof. I tried so much times but failed. Will anybody tell me h

7条回答
  •  [愿得一人]
    2020-12-20 06:11

    Try this:

    internal bool SearchWord(string str, string searchKey)
    {
        int j = 0; bool result = false;
        for (int i = 0; i < str.Length; i++)
        {
            if (searchKey[j] == str[i])
            {
                j++; //count++;
            }
            else { j = 0; }
    
            if (j == searchKey.Length)
            {
                result = true;
                break;
            }
        }
        return result;
    }
    

提交回复
热议问题