模拟实现strstr、strrstr
来源:互联网 发布:iphoto下载 mac 编辑:程序博客网 时间:2024/05/22 12:22
strstr表示在字符串中找子串,其原型为:
char *strstr( const char *string, const char *strCharSet );
这个函数的含义是是,在string中找strCharSet第1次出现的位置,并返回一个指向该位置的指针。如果strCharSet并没有完整的出现在string的任何位置,函数返回一个NULL指针,如果函数的第二个参数为一个空字符串,函数则返回string。
标准函数库里面并没有strrstr这个函数,这个函数的含义便是在第一个字符串找第二个字符串最后一次出现的位置,原理与strstr相同。
下面我们来模拟实现这两个函数,从而加强对这个函数的了解,
**//模拟实现strstr(在字符串中查找一个子串)(在s1中查找s2第一次出现的位置)**
#include<stdio.h>#include<stdlib.h>#include<assert.h>char *my_strstr(const char *str, const char *substr){ assert(str); assert(substr); char*s1 = str; char*s2 = substr; char*cur = str;//当前位置 while (*cur) { s1 = cur; s2 = substr; while (*str == *substr) { str++; substr++; } if (*substr == NULL) { return (char*)str; } else return NULL; }}int main(){ char *arr = "abefcdef"; char*buf = "h"; char*ret=strstr(arr, buf); if (ret != NULL) { printf("%s", ret); } else { printf("NULL"); } system("pause"); return 0;}
**//模拟实现strrstr(在字符串中查找一个子串)(在s1中查找s2最后一次出现的位置)**
#include<stdio.h>#include<stdlib.h>#include<assert.h>const char*my_strrstr(const char *sub, const char*substr){ int i = 0; int j = 0; const char*ret = NULL; for (i = 0; sub[i] != 0; i++) { for (j = 0; substr[j] != 0; j++) { if (sub[i + j] != substr[j]) break; } if (substr[j] == 0) { ret = sub + i; } } return ret;}int main(){ const char *arr = "abefcdef"; const char*buf = "ef"; char*ret = my_strrstr(arr, buf); if (ret != NULL) { printf("%s\n", ret); } else { printf("NULL"); } system("pause"); return 0;}
阅读全文
0 0
- 模拟实现strstr、strrstr
- 模拟实现strchr,strrchr,strstr,strrstr函数
- 模拟实训strstr,strrstr
- 模拟strstr函数strrstr函数
- 模拟实现strrstr
- 模拟实现strrstr
- C语言模拟实现strncpy、strncpy、strncat、strstr和strrstr函数实现
- 【C语言】模拟实现strchr,strrchr,strrstr.
- 有趣的字符查找函数模拟strstr和strrstr,strchr和strrchr
- 模拟实现strstr函数
- 模拟实现strstr函数
- 模拟实现strstr函数
- 模拟实现strstr
- 模拟实现strstr
- 模拟实现strstr函数
- 模拟实现strstr函数
- 模拟实现strstr()函数
- 模拟实现strstr函数
- 将myeclipse中web项目导入eclipse中运行
- String、StringBufer和StringBuilder
- C
- 交换类排序:冒泡排序和快速排序
- 配置host文件
- 模拟实现strstr、strrstr
- spring+cxf发布服务报错Error creating bean with name 'org.apache.cxf.jaxws.spring.NamespaceHandler$SpringSe
- 以POST方式访问wcf方法
- IntelliJ IDEA 配置Gradle运行SpringBoot Web项目(tomcat容器)
- Android程序员学WEB前端(2)-HTML(2)-锚点链接列表表单-Sublime
- PHP isset()与empty()的使用区别详解
- node连接数据库mysql
- ubuntu c++ 连接mysql
- MyEclipse、Tomcat、Maven、SVN环境搭建