简体   繁体   中英

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 .

A sample algo:

  1. Define an array (say destarr[128] , for example) large enough to hold the result (concatenated string).
  2. memset() the destarr to 0 .
  3. use strcat(destarr, a) and strcat(destarr, b) to concatenate one after another.

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 . 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.

Header - string.h

If you want to do that without strcat function then you can write a simple function -

  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';
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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