zoukankan      html  css  js  c++  java
  • 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;
            }
     
    做个快乐的自己。
  • 相关阅读:
    2019/09/26,经济和科技
    失败的总和
    2019/11/05,现代人的焦虑
    2019/09/16,回忆和希望
    2019/09/13,捷径
    演讲手势
    因果谬论和基于数据的另一种说法
    文本框输入事件:onchange 、onblur 、onkeyup 、oninput
    开关按钮切换
    全选,反选,全不选
  • 原文地址:https://www.cnblogs.com/Jessy/p/1867082.html
Copyright © 2011-2022 走看看