查找子串

  • int mySubstr(char *str, char * subStrstr)
  • void test011()
  • int main(void)
这里在mySubstr()中声明两个临时指针进行子串比较
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <Windows.h>

int ret = 0;

int mySubstr(char *str, char * subStrstr) {
	int num=0;

	while (*str != '\0')
	{
		if (*str != *subStrstr) {
			num++;
			str++;
			continue;
		}
		//声明两个局部指针

		char* ptr = str;
		char* subPtr = subStrstr;

		while (*subPtr != '\0')
		{
			if (*ptr != *subPtr)
			{
				num++;
				str++;
				break;
			}
			ptr++;
			subPtr++;
		}
		if (*subPtr == '\0')
		{
			return num;
		}
	}

	return -1;

}

void test011() {
	char str[] = "abcdsgsdnfhisdfd";

	char subStrstr[] = "dnf";

	ret = mySubstr(str, subStrstr);

	if (ret != -1)
	{
		printf("子串在主串中的位置:%d", ret);
	}
	else {
		printf("未找到子串");
	}


}

int main(void)
{
	test011();

	system("pause");
	return EXIT_SUCCESS;
}


版权声明:本文为potato_grow原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/potato_grow/article/details/117730405