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

前端 未结 7 1423
时光取名叫无心
时光取名叫无心 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:20

    Sorry.. thought this would be a fun exercise for me, so...

    Spoiler

    class Program
    {
        static void Main(string[] args)
        {
            string str = "abcdefg";
            string substr = "cde";
            int index = IndexOf(str, substr);
            Console.WriteLine(index);
            Console.ReadLine();
        }
    
        private static int IndexOf(string str, string substr)
        {
            bool match;
    
            for (int i = 0; i < str.Length - substr.Length + 1; ++i)
            {
                match = true;
                for (int j = 0; j < substr.Length; ++j)
                {
                    if (str[i + j] != substr[j])
                    {
                        match = false;
                        break;
                    }
                }
                if (match) return i;
            }
    
            return -1;
        }
    }
    

提交回复
热议问题