在C语言中,连接两个字符串的方法有以下几种:
char *strcat(char *dest, const char *src);
示例代码:
#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;
}
输出结果:
Concatenated string: Hello World!
char *strcpy(char *dest, const char *src);
示例代码:
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello";
char str2[] = " World!";
strcpy(str1 + strlen(str1), str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
输出结果:
Concatenated string: Hello World!
int sprintf(char *str, const char *format, ...);
示例代码:
#include <stdio.h>
int main() {
char str1[50] = "Hello";
char str2[] = " World!";
sprintf(str1 + strlen(str1), "%s", str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
输出结果:
Concatenated string: Hello World!
需要注意的是,上述方法连接字符串时,要确保第一个字符串具有足够的空间来容纳连接后的字符串,以防止缓冲区溢出。