深入理解strstr
strstr作用展示:
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "This is a simple string";
char* pch;
pch = strstr(str, "simple");
/*strncpy(pch, "sample", 6);*/
printf("%s\n",pch);
return 0;
}
结果:
文章来源:https://www.toymoban.com/news/detail-705298.html
模拟实现:文章来源地址https://www.toymoban.com/news/detail-705298.html
//模拟实现strstr
#include<stdio.h>
const char* my_strstr(const char* str1, const char* str2) {
const char* cp = str1;
const char* s1 = NULL;
const char* s2 = NULL;
while (*cp) {//cp的作用是记录可能找到匹配的字符串的起始位置
s1 = cp;
s2 = str2;
while (*s1 == *s2 && *s1 != '\0' && *s2 != '\0') {
s1++;
s2++;
}
if (*s2 == '\0') {
return cp;
}
cp++;
}
return NULL;
}
int main() {
char arr1[] = "abbcdef";
char arr2[] = "bbc";
char*ret=my_strstr(arr1, arr2);
if (ret != NULL) {
printf("%s\n", ret);
}
else
printf("error\n");
return 0;
}
到了这里,关于c语言练习44:深入理解strstr的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!