Concatenate Strings in C Language

To concatenate strings in C Language, we can use any of the following ways.

  • strcat(str1, str2) function concatenates string str2 to string str1.
  • Use a looping statement to concatenate each character from the second string to the first string.

Concatenate Strings using strcat() Function

In the following program, we read two strings from user into str1 and str2, and concatenate the string str2 to str1 using strcat() function.

Include string.h to use strcat() function.

main.c

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

int main() {
    char str1[30], str2[30];
    
    printf("Enter first string   : ");
    scanf("%s", str1);
    
    printf("Enter second string  : ");
    scanf("%s", str2);
    
    strcat(str1, str2);
    printf("Result string        : %s\n", str1);
    
    return 0;
}

Output

Enter first string   : apple
Enter second string  : banana
Result string        : applebanana
Program ended with exit code: 0
ADVERTISEMENT

Concatenate Strings using Loop Statement

In the following program, we read two strings from user into str1 and str2, and concatenate the string str2 to str1 using For Loop statement.

Refer C For Loop tutorial.

main.c

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

int main() {
    char str1[30], str2[30];
    
    printf("Enter first string   : ");
    scanf("%s", str1);
    
    printf("Enter second string  : ");
    scanf("%s", str2);
    
    unsigned long len1 = strlen(str1);
    unsigned long len2 = strlen(str2);
    for (int i = 0; i < len2; i++) {
        str1[i + len1] = str2[i];
    }
    printf("Result string        : %s\n", str1);
    
    return 0;
}

Output

Enter first string   : cherry
Enter second string  : mango
Result string        : cherrymango
Program ended with exit code: 0

Conclusion

In this C Tutorial, we learned how to concatenate two strings using different ways with examples.