How can two strings be concatenated in the C language?

In C language, you can use the strcat function to concatenate two strings.

The prototype of the strcat function is as follows:

char* strcat(char* dest, const char* src);

In this case, ‘dest’ is the target string and ‘src’ is the string to be appended. The ‘strcat’ function appends the content of ‘src’ to the end of ‘dest’ and returns the address of ‘dest’.

Below is an example program demonstrating how to use the strcat function to concatenate two strings.

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

int main() {
    char dest[100] = "Hello, ";
    const char src[] = "world!";
    
    strcat(dest, src);
    
    printf("连接后的字符串为:%s\n", dest);
    
    return 0;
}

In the example above, a character array named dest with a size of 100 is first defined and initialized as “Hello, “. Then a constant string src is defined as “world!”. Next, the strcat function is called to append the content of src to the end of dest. Finally, the printf function is used to print the concatenated string.

Run the program and the output will be:

连接后的字符串为:Hello, world!

As can be seen, the concatenated string is “Hello, world!”.

bannerAds