字符串操作之查找子串

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//优化思路 memcpy(str,substr,3)==0;
int myStrstr(char *str,char *subStr){
	int num = 0;
	while (*str != '\0'){
		if (*str != *subStr){
			str++;
			num++;
			continue;
		}
		//创建临时指针
		char *tmpStr = str;
		char *tmpSubStr = subStr;
		while (*tmpSubStr!='\0')
		{
			if (*tmpStr != *tmpSubStr){
				//匹配失败
				str++;
				num++;
				break;
			}
			tmpStr++;
			tmpSubStr++;
		}
		if (*tmpSubStr == '\0'){
			//匹配成功
			return num;
		}
	}
	return -1;
}

void test01(){
	char *str = "abcdefgdnf";
	int ret = myStrstr(str,"dnf");
	if (ret == -1){
		printf("未找到子串\n");
	}
	else
	{
		printf("找到了子串,位置为%d\n",ret);
	}
}
int main(){
	test01();
	return 0;
}
发布了122 篇原创文章 · 获赞 58 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_39112646/article/details/102712655