自定义函数实现查找子串的功能

实现功能

实现查找子串功能
在字符串中查找对应的子串,如果有返回字符串第一个字母的位置,如果没有返回-1

测试源码

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>



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();

	system("pause");
	return EXIT_SUCCESS;
}

测试结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zxy131072/article/details/89670391