简体   繁体   English

连接两个数组

[英]Concatenating two arrays

I was trying to create a program that takes in two arrays and concatenates them to create a new string. 我试图创建一个接受两个数组并将它们连接起来以创建新字符串的程序。 These are the two strings. 这是两个字符串。

 char a[8]={"hellostr"};
 char b[8]={"HELLOSTR"};

Can someone tell me how could I concatenate and display this concatenated string? 有人可以告诉我如何串联并显示此串联的字符串吗? I tried looking for it but could not understand much of it. 我尝试寻找它,但对它了解不多。

You need to make use of strcat() function from string.h . 您需要使用string.hstrcat()函数。

A sample algo: 样本算法:

  1. Define an array (say destarr[128] , for example) large enough to hold the result (concatenated string). 定义一个足够大的数组(例如destarr[128] )以容纳结果(连接的字符串)。
  2. memset() the destarr to 0 . memset() destarr0
  3. use strcat(destarr, a) and strcat(destarr, b) to concatenate one after another. 使用strcat(destarr, a)strcat(destarr, b)彼此串联。

That said, 那就是

 char a[ ]={"hellostr"};

is considered better and less error-prone over 被认为是更好的,并且不易出错

char a[8]={"hellostr"};

as, 如,

  • In the former case, compiler takes the charge to allocate the memory, as required, with the null-terminator in mind . 在前一种情况下,编译器要负责根据需要分配内存,同时要注意 null终止符。 The array can be used as a string . 该数组可以用作字符串
  • In the later case, there is no room for the null-terminator and hence, the array can neither be considered nor be used as a string . 在后一种情况下,没有空终止符的余地,因此,既不能将数组视为字符串,也不能将其用作字符串

strcat function can be used. 可以使用strcat函数。

Header - string.h 标头string.h

If you want to do that without strcat function then you can write a simple function - 如果您想在没有strcat函数的情况下执行此操作,则可以编写一个简单的函数-

  void concatenate(char a[], char b[])
  {
     int c, d;

      c = 0;

     while (a[c] != '\0')
   {
        c++;    
   }

     d = 0;

   while (b[d] != '\0') 
    {
       a[c] = b[d];
       d++;
       c++; 
    }

       a[c] = '\0';
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM