【C编程】合并两个字符集合为一个新集合,每个字符串在新集合中仅出现一次,函数返回新集合中字符串。

/*合并两个字符集合为一个新集合,每个字符串在新集合中仅出现一次,函数返回新集合中字符串。
    如:
      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;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值