查找字符串子串

实验目标: 手动书写一个strstr()查找子串的函数

实验案例:

有一个字符串 "abcdefgdfnfasdaf" ,查找字符串中是否含有子串“dnf”,如果有返回字符子串在字符串的位置,如果没有返回-1。

#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 = "abcdefgdfnfasdaf";
	int ret = myStrstr(str, "dnf");
	if (ret != -1) {
	
		printf("找到字符串:位置为%d\n", ret);
	}
	else {

		printf("未找到字符串\n");
	}
}

int main() { 

	test01();

	system("pause"); 
	return EXIT_SUCCESS; 
} 

猜你喜欢

转载自blog.csdn.net/weixin_56067923/article/details/128600126