You are here

C program to concatenate strings

C program to concatenate two strings, for example, if the first string is "C programming" and the second string is " language" (note space before language) then on concatenating these two strings we get the string "C programming language." To concatenate two strings we use strcat function of string.h, to concatenate without using library function see another code below which uses pointers.

C programming code

  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. int main()
  5. {
  6.   char a[1000], b[1000];
  7.  
  8.   printf("Enter the first string\n");
  9.   gets(a);
  10.  
  11.   printf("Enter the second string\n");
  12.   gets(b);
  13.  
  14.   strcat(a, b);
  15.  
  16.   printf("String obtained on concatenation: %s\n", a);
  17.  
  18.   return 0;
  19. }

Output of program:
String concatenation

Download String Concatenation program.

Concatenate strings without strcat function

C program to concatenate strings without using library function strcat of string.h header file. We create our own function.

  1. #include <stdio.h>
  2.  
  3. void concatenate(char [], char []);
  4.  
  5. int main()
  6. {
  7.    char p[100], q[100];
  8.  
  9.    printf("Input a string\n");
  10.    gets(p);
  11.  
  12.    printf("Input a string to concatenate\n");
  13.    gets(q);
  14.  
  15.    concatenate(p, q);
  16.  
  17.    printf("String obtained on concatenation: \"%s\"\n", p);
  18.  
  19.    return 0;
  20. }
  21.  
  22. void concatenate(char p[], char q[]) {
  23.    int c, d;
  24.    
  25.    c = 0;
  26.  
  27.    while (p[c] != '\0') {
  28.       c++;      
  29.    }
  30.  
  31.    d = 0;
  32.  
  33.    while (q[d] != '\0') {
  34.       p[c] = q[d];
  35.       d++;
  36.       c++;    
  37.    }
  38.  
  39.    p[c] = '\0';
  40. }

The first for loop in concatenate function is calculating string length, you can also use strlen function if you wish.

String concatenation using pointers

  1. #include <stdio.h>
  2.  
  3. void concatenate_string(char*, char*);
  4.  
  5. int main()
  6. {
  7.     char original[100], add[100];
  8.    
  9.     printf("Enter source string\n");
  10.     gets(original);
  11.    
  12.     printf("Enter string to concatenate\n");
  13.     gets(add);
  14.    
  15.     concatenate_string(original, add);
  16.    
  17.     printf("String after concatenation: \"%s\"\n", original);
  18.        
  19.     return 0;
  20. }
  21.  
  22. void concatenate_string(char *original, char *add)
  23. {
  24.    while(*original)
  25.       original++;
  26.      
  27.    while(*add)
  28.    {
  29.       *original = *add;
  30.       add++;
  31.       original++;
  32.    }
  33.    *original = '\0';
  34. }