编辑代码

#include<stdio.h>
#include<assert.h>
#include<string.h>
 
int SMATCH(char* AStr, char* BStr)// AStr代表串1,BStr代表串2
{
	assert( AStr&&BStr);//断言
	if (AStr == NULL || BStr == NULL)//串为空值时直接返回-1
	{
		return -1;
	}
	int i = 0;//遍历串1
	int j = 0;//遍历串2
	int lenstr = strlen(AStr);//求出串1的长度
	int lensub = strlen(BStr);//求出串2的长度
	while ((i < lenstr) && (j < lensub))//当串1遍历结束或串2遍历结束时,跳出循环
	{
		if (str[i] == sub[j])//匹配成功
		{
			i++;
			j++;
		}
		else//匹配失败
		{
			i = i - j + 1;
			j = 0;
		}
	}
	if (j >= lensub)//如果是因为子串遍历结束而跳出循环,说明匹配成功,返回下标
	{
		return i - j;
	}
	else//匹配失败,返回-1
		return -1;
}
int main()
{
	printf("%d\n", SMATCH("ABCDE", "BCD"));//匹配成功,返回的下标1
	printf("%d\n", SMATCH("ABCDE", "CD"));//匹配成功,返回的下标2
	printf("%d\n", SMATCH("ABCDE", "F"));//匹配失败,返回-1
 
	return 0;
}