如何在一个阵列中组合2个阵列

时间:2014-12-08 13:09:59

标签: c arrays

作为编程新手,我有一个问题给你的人,

为了没有任何特定目的,我想知道我是否从用户那里拿出2个数组,而不是将它们放在一个单独的数组中,我怎样才能避免在后一个数组中使用2个相同的字符?

为了澄清,让我们说用户输入“sea”和“blue”作为2个单独的数组,

如何将它们组合在一个数组中,如“s,e,a,b,l,u”而不是“C,e,a,b,l,u,e”中的C编程语言? / p>

2 个答案:

答案 0 :(得分:1)

我希望你不要用逗号分隔目标数组中的字符。

这是一个例子

#include <stdio.h>
#include <string.h>

int main( void )
{
    char s1[] = "sea";
    char s2[] = "blue";
    char s3[sizeof( s1 ) + sizeof( s2 ) - 1];
    char *p, *q;

    strcpy( s3, s1 );
    p = s3 + strlen( s1 );

    for ( q = s2; *q; ++q )
    {
        if ( strchr( s1, *q ) == NULL )
        {
            *p++ = *q;
        }
    }

    *p = '\0';

    puts( s1 );
    puts( s2 );
    puts( s3 );

    return 0;
}

输出

sea
blue
seablu

或者,如果您希望目标数组可以包含两个(或更多)源数组的唯一字符,那么代码可能看起来像

#include <stdio.h>
#include <string.h>

int main()
{
    char s1[] = "sea";
    char s2[] = "blue";
    const char * a[] = { s1, s2 };
    char s3[sizeof( s1 ) + sizeof( s2 ) - 1];
    size_t i;
    char *p, *q;

    p = s3;

    for ( i = 0; i < sizeof( a ) / sizeof( *a ); i++ )
    {
        const char *q = a[i];
        for ( ; *q; ++q )
        {
            char *t = s3;

            while ( t != p && *t != *q ) ++t;
            if ( t == p )
            {
                *p++ = *q;
            }
        }
    }

    *p = '\0';

    puts( s1 );
    puts( s2 );
    puts( s3 );

    return 0;
}

输出与上面相同。

考虑到如果要用

之类的零初始化目标数组
char s3[sizeof( s1 ) + sizeof( s2 ) - 1] = { '\0' };

然后代替循环

while ( t != p && *t != *q ) ++t;

你可以像第一个示范程序一样使用函数strchr

答案 1 :(得分:0)

做类似的事情:

int is_in_array(char *str, char c)
{
  int i;
  i = 0;
  while (str[i] != '\0')
    {
      if (str[i] == c)
        return 1;
      i++
    }
  return 0;
}

int arraySize(char *str)
{
  int i;

  i = 0;
  while (str[i] != '\0')
    i++;
  return i;
}
int add_array(char *str1, char *str2)
{
  int i;
  int j;
  int size;
  char *str_all;

  size = arraySize(str1) + arraySize(str2);
  str_all = malloc(size * sizeof(str_all*));
  while (str1[i] != '\0')
    {
      str_all[i] = str1[i];
      i++;
    }
  j = 0;
  while (str2[i] != '\0')
    {
      if (is_in_array(str1, str2[j]) == 0)
        {
          str_all[i] = str2[j];
          i++;
        }
      j++;
    }
}
相关问题