strstr()的简单实现

本文提供了strstr()函数的两种实现方式:一种是使用C语言,另一种是使用C#语言。这两种实现都展示了如何在一个字符串中查找另一个字符串,并返回找到的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

strstr()的简单实现

strstr(s1,s2)是一个经常用的函数,他的作用就是在字符串s1中寻找字符串s2如果找到了就返回指针,否则返回NULL。
下面是这个函数的一个简单实现:
ExpandedBlockStart.gif代码
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;
        }
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值