strstr实现


今天面试时遇到了,写一遍。
返回字符串str1中字符串str2第一次出现的位置。
#include 
#include 
using namespace std;

//字串查找
int mystrstr(char* str1, char* str2)
{
	if (str1 == NULL || str2 == NULL || str1 == "" || str2 == "")
	{
		return -1;
	}
	char* orginstr = str1;
	char* substr = str2;
	int sublength = strlen(str2);
	char* pos = NULL;
	int position = -1;



	while (*orginstr != '\0')
	{
		if (*orginstr == *substr && *substr != '\0' && *orginstr !='\0')
		{
			orginstr++;
			substr++;
			if (*substr == '\0')
			{
				pos = orginstr - sublength;
				break;
			}
		}
		else
		{
			orginstr++;
			substr = str2;
		}
	}
	if (*substr == '\0')
	{
		position = pos - str1; //索引从零开始计数
	}
	return position;
}
void test(char* p1, char* p2, int exepcted)
{
	int sIndex = mystrstr(p1, p2);
	if (sIndex == exepcted)
	{
		
		printf("test passed\n");
	}
	else
	{
		cout << "sIndex = " << sIndex << endl;
		printf("test not passed\n");
	}
}

int main()
{
	char *p1 = (char*)"abcdabefg";
	char *p2 = (char*)"bc";
	test(p1, p2, 1);

	p2 = (char*)"aaaaa";
	test(p1, p2, -1);

	p2 = (char*)"a";
	test(p1, p2, 0);

	p2 = NULL;
	test(p1, p2, -1);


	return 0;
}

strstr实现_第1张图片

你可能感兴趣的:(面试)