c语言练习44:深入理解strstr

深入理解strstr

c语言练习44:深入理解strstr_第1张图片

strstr作用展示:

#include 
#include 
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;
}

 结果:

c语言练习44:深入理解strstr_第2张图片

模拟实现:

//模拟实现strstr
#include
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语言,算法,开发语言)