/*合并两个字符集合为一个新集合,每个字符串在新集合中仅出现一次,函数返回新集合中字符串。
如:
s1集合{“while”,”for”,”switch”,”if”,"break",”continue”}
s2集合{“for”,”case”,”do”,”else”,”char”,”switch”}
运行结果:
while for switch if break continue case do else char
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 20
int my_merge(char **str1,char **str2,char *result[])
{
int count = 0;
int i = 0;
int j = 0;
int flag = 1;
for(i = 0;i < 6;i++)
{
strcpy(result[count],str1[i]);
count++;
}
for(i = 0;i < 6;i++)
{
for(j = 0;j < 6;j++)
{
if(strcmp(str2[i],str1[j]) == 0) //判断str2是否和str1中的字符串有相同
{
flag = -1;
break;
}
else
{
flag = 1;
}
}
if(flag == 1) //如果不相同。则将str2的值放入result数组中
{
strcpy(result[count],str2[i]);
count++;
}
}
return count;
}
int main()
{
char *str1[6] = {"while","for","switch","if","continue","break"};
char *str2[6] = {"for","case","do","else","char","switch"};
char *result[N] = {0};
int count = 0; //数结果的行数
int i = 0;
for(i = 0;i < N;i++) //给指针数组分配内存空间
{
result[i] = (char *)malloc(sizeof(char)*20);
}
count = my_merge(str1,str2,result);
printf("the result is:\n");
for(i = 0;i < count;i++)
{
printf("%s ",result[i]);
}
printf("\n");
for(i = 0;i < N;i++)
{
free(result[i]);
}
return 0;
}
【C编程】合并两个字符集合为一个新集合,每个字符串在新集合中仅出现一次,函数返回新集合中字符串。
最新推荐文章于 2024-03-13 21:13:48 发布