Linux_C练习:判断一个字符串是不是另一个字符串的子串;(比如"ab"是"aabcd"的子串)

#include
#include
#include

int com(char *p, char *q, int n, int m)
{
	int i, j;
	char *tmp = (char *)malloc(sizeof(char) * 20);
	if(NULL == tmp)
	{
		printf("error\n");
		exit(1);
	}
	char *tmp1 = tmp;
	char *tmp2 = q;
	char *tmp3 = p;
	int flag = 0;
	if(n < m)
	{
		for(i = 0; i <= m - n; ++i )
		{
			q = q + i;
			for(j = i; j< i + n; ++j)
			{
				
				*tmp++ = *q++;
			}
			tmp = tmp1;
			if(strcmp(tmp, p) == 0)
			{
				flag = 1;
			}
			q = tmp2;
		}	

	}
    if(n > m)
	{
		for(i = 0; i <= n - m; ++i )
		{
			p = p + i;
			for(j = i; j< i + m; ++j)
			{
				
				*tmp++ = *p++;
			}
			tmp = tmp1;
			if(strcmp(tmp,q) == 0)
			{
				flag = 2;
			}
			p = tmp3;
		}	

	}
	if(n == m)
	{
		if(strcmp(p, q) == 0)
		{
			flag = 3;
		}
	}
	return flag;
}

int main()
{
	int l, l1;
	char *p = (char *)malloc(sizeof(char) * 20);
	char *q = (char *)malloc(sizeof(char) * 20);
	int flag;
	if(NULL == p || NULL == q)
	{
		printf("NULL error\n");
		exit(1);
	}
	printf("请输入第一个字符串\n");
	scanf("%s", p);
	printf("请输入第二个字符串\n");
	scanf("%s", q);
	l = strlen(p);
	l1 = strlen(q); 
	flag = com(p, q, l, l1);
	switch(flag)
	{
		case 0: printf("两字符串互不为对方的子串\n");
				break;
		case 1: printf("第一个字符串为第二个的子串\n");
				break;
		case 2: printf("第二个字符串为第一个的子串\n");
				break;
		case 3: printf("互为子串\n");
				break;
		default: printf("111\n");
				break;
	}
	return 0;
}

你可能感兴趣的:(Linux_C练习:判断一个字符串是不是另一个字符串的子串;(比如"ab"是"aabcd"的子串))