strstr()的简单实现

strstr()的简单实现

strstr(s1,s2)是一个经常用的函数,他的作用就是在字符串s1中寻找字符串s2如果找到了就返回指针,否则返回NULL。
下面是这个函数的一个简单实现:
代码
static const char* _strstr(const char* s1, const char* s2)
{
     assert(s2 
&& s1);
     
const char* p=s1, *r=s2;
     
while(*p!= '\0')
     {
          
while(*p++==*r++);
          
if (*r=='\0')
               
return s1;
          
else
          {
               r
=s2;
               p
=++s1;
          }
     }
     
return NULL;
}

 

c# 实现:

 static int StrStr(string a, string b)
        {
            int indexA = 0;
            int indexB = 0;

            if (a == null || b == null || a.Length <b.Length)
            {
                return -1;
            }

            while (indexA < a.Length)
            {
                int temp = indexA;

                while (indexA< a.Length
                      && indexB < b.Length
                      &&a[indexA] == b[indexB])
                {
                    indexA++;
                    indexB++;
                }

                if (indexB == b.Length)
                {
                    return temp;
                }
                else
                {
                    indexB = 0;
                    indexA = temp + 1;
                }
            }

            return -1;
        }
 
做个快乐的自己。
原文地址:https://www.cnblogs.com/Jessy/p/1867082.html