concatenate two strings in c

Concatenating Two Strings in C

To concatenate two strings in C, you can use the strcat() function from the C standard library. Here are the steps to concatenate two strings:

  1. Declare two character arrays to store the strings you want to concatenate. Make sure the arrays have enough space to hold the combined string, including the null terminator.
  2. Initialize the first array with the first string.
  3. Use the strcat() function to concatenate the second string to the first string. The strcat() function appends the characters of the second string to the end of the first string.
  4. Print or use the concatenated string as needed.

Here's an example that demonstrates the steps:

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

int main() {
    char str1[50] = "Hello";
    char str2[] = " World!";

    strcat(str1, str2);

    printf("Concatenated string: %s\n", str1);

    return 0;
}

In this example, the str1 array is initialized with the string "Hello", and the str2 array is initialized with the string " World!". The strcat() function is then used to concatenate str2 to the end of str1. Finally, the concatenated string is printed.

The output of this program will be:

Concatenated string: Hello World!

Please note that it is important to ensure that the destination array (str1 in this example) has enough space to accommodate the concatenated string. If the destination array is not large enough, it can lead to buffer overflow and undefined behavior.

I hope this helps! Let me know if you have any further questions.