在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!
需要注意的是,上述方法連接字符串時,要確保第一個字符串具有足夠的空間來容納連接后的字符串,以防止緩沖區溢出。