C语言学习历程——编程练习2——08

来源:互联网 发布:淘宝靠谱的aj 编辑:程序博客网 时间:2024/05/22 14:56
   8.合并两个字符集合为一个新集合,每个字符串在新集合中仅出现一次,函数返回新集合中字符串。
    如: s1集合{“while”,”for”,”switch”,”if”,”continue”}
s2集合{“for”,”case”,”do”,”else”,”char”,”switch”}
    运行结果:

         while   for   switch   if  break   continue   case  do  else  char


分析:先把第一个字符串放入新的数组,放第二个时候,检查重复的字符串,去除重复的字符串,其余的放入新的数组


下面是代码实现:


/***************************************************************************************
   合并两个字符集合为一个新集合,每个字符串在新集合中仅出现一次,函数返回新集合中字符串。
    如: 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>
 
int mystrcmp(const char *str1, const char *str2)  //比较两个字符串的大小,大于则返回正数,小于负数,等于返回0
{
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;
}

0 0
原创粉丝点击