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;
            }
     
    做个快乐的自己。
  • 相关阅读:
    报错处理——TypeError: Dog() takes no arguments
    python笔记——爬虫练习
    python笔记——爬虫原理
    Numpy入门练习
    python学习资源
    python笔记——函数的参数(位置参数、默认参数、可变参数、关键字参数、命名关键字参数、参数组合)
    Spyder快捷键
    python笔记——常用的内置函数
    python笔记——dict和set
    python笔记——for和while循环、if条件判断、input输入
  • 原文地址:https://www.cnblogs.com/Jessy/p/1867082.html
Copyright © 2011-2022 走看看