朴素匹配算法-子字符串的查找

    class test 

    {

        /*

            检索某字符串s在另一字符串str中,第pos位之后是否存在,存在则返回第一次出现的位置,不存在返回-1

         */

        static void Main(string[] args)

        { 

            String str=”apple”;

            int n=searchIndex(str,”pl”, 4);

            if(n>=0)

            Console.Write(n);

            Console.Read();

        

        

        }

        static int searchIndex(String str, String s, int pos) 

        {

            int m=str.Length;

            int n=s.Length;

            if (m < n)

            {

                Console.Write(“要检索的目标字符串长度大于被检索字符串”+’\n’);

            }

            else if(pos>m||pos<=0){

                Console.Write(“检索起始位置超出被检索字符串长度” + ‘\n’);

            }

            else 

            {

                for (int i = pos-1; i <= m – n; i++) {

                    String temp = str.Substring(i, n);

                    if (temp.Equals(s)) {

                        return i+1;

                    }

                }

                Console.Write(“未检索到目标字符串”);

            }

            return -1;

        }

点赞