如: s1集合{“while”,”for”,”switch”,”if”,”continue”}
s2集合{“for”,”case”,”do”,”else”,”char”,”switch”}
运行结果:
while for switch if break continue case do else char
#include <stdio.h>
#include <stdlib.h>
//比较两个字符串的大小,大于则返回正数,小于负数,等于返回0
int mystrcmp(const char *str1, const char *str2)
{
while (*str1 == *str2)
{
if (*str1 == '\0')
{
return 0;
}
str1++;
str2++;
}
return (*str1 - *str2);
}
//合并两个字符串,去除重复的字符串
int ConbineStr(char **str1, char **str2, char **outbuf)
{
int i = 0;
int j = 0;
int k = 0;
int flag = 0;
char *t = NULL;
char *p = t;
t = (char *)malloc(10 * sizeof(char *));
for (i = 0; i < 5; i++)
{
outbuf[k++] = str1[i]; //先将str1中的字符串放入新的字符串中
}
for (i = 0; i < 6; i++)
{
flag = 0;
p = str2[i];
for (j = 0; j < 5; j++)
{
if (mystrcmp(p, str1[j]) == 0) //遍历第二个字符串数组,与第一个相比较,相同的就做标志1
{
flag = 1;
}
}
if (flag == 0)
{
outbuf[k++] = str2[i]; //去除相同的字符串,放入新的字符串中
}
}
free(t);
return k;
//返回字符串的个数
}
void PrintStr(char **str, int n) //打印字符串数组
{
int i = 0;
for (i = 0; i < n; i++)
{
printf ("%s ", str[i]);
}
printf ("\n");
}
int main()
{
char *str1[] = {"while", "for", "switch", "if", "continue"};
char *str2[] = {"for", "case", "do", "else", "char", "switch"};
char *outbuf[100] = {0}; //用于存放新的字符串数组
int count = 0;
count = ConbineStr(str1, str2, outbuf);
printf ("The original strings are :\n");
PrintStr(str1, 5);
PrintStr(str2, 6);
printf ("\nThe result is :\n");
PrintStr(outbuf, count);
return 0;
}