【嵌入式系统学习记录】练习:判断一个字符串是不是另一个字符串的子串;(比如"ab"是"aabcd"的子串)

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

char *jungle(char *p1, char *p2, int size1, int size2)
{
	int i, n, m;
	char *s1 = "NO!";
	char *s2 = "YES!";
/*	char *temp = (char *)malloc(sizeof(char) * 50);
	char *temp2 = temp;
	if(NULL == temp)
	{
		printf("malloc failure!\n");
		exit(1);
	}*/

	if(size1 <= size2)
	{
		return s1;
	}
	else
	{
		for(n = 0; n < size1 - size2 + 1; ++n)
		{
		/*	for(i = 0; i < size2; ++i)
			{
				*temp++ = *p1++;
			}
				temp = temp2;
			if(strcmp(temp, p2) != 0)
			{	
				temp++;
				for(m = 0; m < size2; ++m)
				{
					p1--;
				}
					p1++;
					*temp = *temp2;
					p1 = p1 -size2 + 1;
			}
			else
			{
				return s2;
				break;
			}*/
			if(strncmp(p2, p1+n, size2) == 0)//strncmp可以实现一定个数的字符串相比较,省去了注释掉的代码,减少了很多代码量
			{
				return s2;
			}
		}
		return s1;
	}

}


int main()
{
	int length1, length2;
	char *father = (char*)malloc(sizeof(char) * 50);
	char *son = (char*)malloc(sizeof(char) * 50);
	printf("please enter a long words:\n");
	scanf("%s",father);
	printf("please enter a short words:\n");
	scanf("%s",son);
	if(NULL == father || NULL == son)
	{
		printf("malloc failure!\n");
		exit(1);
	}
	length1 = strlen(father);
	length2 = strlen(son);
	printf("%s",jungle(father, son, length1, length2));//通过指针传参和返回结果
	free(father);//malloc之后要通过手动释放内存
	free(son);
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值