c语言字符串连接 &
时间: 2023-08-08 15:02:47 浏览: 65
在C语言中,可以使用字符串连接运算符(+)或者库函数strcat()来连接两个字符串。
使用字符串连接运算符(+)可以将两个字符串连接成一个新的字符串。例如:
```c
#include <stdio.h>
int main() {
char str1[] = "Hello";
char str2[] = " World";
char result[100];
strcpy(result, str1); // 将str1复制到result中
strcat(result, str2); // 连接str2到result中
printf("连接后的字符串:%s\n", result);
return 0;
}
```
输出结果为:连接后的字符串:Hello World
另一种方法是使用库函数strcat(),该函数用于将源字符串连接到目标字符串的末尾。例如:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = " World";
char result[100];
strcpy(result, str1); // 将str1复制到result中
strcat(result, str2); // 连接str2到result中
printf("连接后的字符串:%s\n", result);
return 0;
}
```
输出结果为:连接后的字符串:Hello World
需要注意的是,在使用strcat()函数时,要保证目标字符串有足够的空间来存储源字符串的内容。如果目标字符串空间不够,可能会导致字符串溢出的问题。