您的位置:首页 > 其它

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

2018-03-13 23:15 453 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐