在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("%s\n", str1);
return 0;
}
輸出結果為:Hello World!
int sprintf(char *str, const char *format, ...);
示例:
#include <stdio.h>
int main() {
char str[100];
char name[] = "Alice";
int age = 20;
sprintf(str, "My name is %s and I am %d years old.", name, age);
printf("%s\n", str);
return 0;
}
輸出結果為:My name is Alice and I am 20 years old.
#include <stdio.h>
int main() {
char str1[50] = "Hello";
char str2[] = " World!";
int i = 0, j = 0;
while (str1[i] != '\0') {
i++;
}
while (str2[j] != '\0') {
str1[i] = str2[j];
i++;
j++;
}
str1[i] = '\0';
printf("%s\n", str1);
return 0;
}
輸出結果為:Hello World!
這些方法可以根據實際需求選擇適合的方法進行字符串拼接。