实现自己的strstr函数

来源:互联网 发布:linux远程连接工具 编辑:程序博客网 时间:2024/05/18 02:24

实现自己的strstr函数:返回主串中子字符串的位置后的所有字符。

如:主串“12345678”,字串“45”,函数返回“45678”

[cpp] view plaincopy
  1. #include <stdio.h>  
  2.   
  3. const char *my_strstr(const char *str, const char *sub_str)  
  4. {  
  5.     for(int i = 0; str[i] != '\0'; i++)  
  6.     {  
  7.         int tem = i; //tem保留主串中的起始判断下标位置   
  8.         int j = 0;  
  9.         while(str[i++] == sub_str[j++])  
  10.         {  
  11.             if(sub_str[j] == '\0')  
  12.             {  
  13.                 return &str[tem];  
  14.             }  
  15.         }  
  16.         i = tem;  
  17.     }  
  18.   
  19.     return NULL;  
  20. }  
  21.   
  22. int main()  
  23. {  
  24.     char *s = "1233345hello";  
  25.     char *sub = "345";  
  26.     printf("%s\n", my_strstr(s, sub));  
  27.     return 0;  
  28. }  
0 0
原创粉丝点击