strstr函数的自己实现

请用标准C语言实现下列标准库函数,设计中不得使用其他库函数。
char *strstr(char *str1,char *str2);

在字符串str1中,寻找字串str2,若找到返回找到的位置,否则返回NULL

[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <cassert>  
  3. using namespace std;  
  4.   
  5.   
  6. const char* StrStr(const char *str1, const char *str2)  
  7. {  
  8.       assert(NULL != str1 && NULL != str2);  
  9.         
  10.        
  11.       while(*str1 != '\0')  
  12.       {  
  13.           const char *p = str1;  
  14.           const char *q = str2;  
  15.           const char *res = NULL;  
  16.           if(*p == *q)  
  17.           {  
  18.                 res = p;  
  19.                 while(*p && *q && *p++ == *q++)  
  20.                 ;  
  21.                   
  22.                 if(*q == '\0')  
  23.                       return res;                      
  24.           }  
  25.           str1++;  
  26.       }  
  27.       return NULL;  
  28. }  
  29.   
  30.   
  31. int main()  
  32. {  
  33.     const char *str1 = "wangyang";  
  34.     const char *str2 = "ang";  
  35.     const char *res = StrStr(str1, str2);  
  36.       
  37.     if(res != NULL)  
  38.             cout<<res<<endl;  
  39.     else  
  40.         cout<<"NOT"<<endl;  
  41.           
  42.     system("pause");  
  43.               
  44. }  
`strstr` 函数是 C 语言标准库中的一个字符串处理函数,它的原型在 `string.h` 头文件中声明。这个函数用于在字符串中查找第一次出现的子串,并返回子串首次出现的位置的指针。如果未找到子串,则返回NULL指针。 函数原型如下: ```c char *strstr(const char *str1, const char *str2); ``` 参数说明: - `str1`:目标字符串,`strstr` 函数会在这个字符串中查找 `str2`。 - `str2`:需要查找的子串。 返回值: - 返回一个指向第一次出现 `str2` 的子串的指针,如果 `str2` 不是 `str1` 的子串,则返回NULL。 这个函数是大小写敏感的。 下面是一个简单的 `strstr` 函数实现示例: ```c #include <stdio.h> #include <string.h> char *my_strstr(const char *str1, const char *str2) { if (*str2 == '\0') { return (char *)str1; } const char *p1 = str1; const char *p2; while (*p1) { p2 = str2; while (*p1 && *p2 && (*p1 == *p2)) { p1++; p2++; } if (!*p2) { return (char *)str1; } str1++; } return NULL; } int main() { const char *str = "Hello, world!"; const char *to_find = "world"; char *found = my_strstr(str, to_find); if (found != NULL) { printf("子串 '%s' 在 '%s' 中首次出现于位置: %ld\n", to_find, str, found - str); } else { printf("在 '%s' 中未找到 '%s'\n", str, to_find); } return 0; } ``` 在这个实现中,我们手动遍历 `str1` 来查找 `str2`,当找到 `str2` 的第一个字符时,再逐个比较后续的字符,直到发现不匹配的字符或者到达 `str1` 或 `str2` 的结尾。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值