C语言如何连接两个字符串
在C语言中,连接两个字符串可使用`strcat()`函数还是手动实现。
1. 使用`strcat()`函数:
`strcat()`函数用于连接两个字符串,将第二个字符串追加到第一个字符串的末尾。
```c
#include
#include
int main() {
char str1[100] = "Hello";
char str2[50] = " World";
strcat(str1, str2);
printf("连接后的字符串:%s
", str1);
return 0;
}
```
输出结果为:
```
连接后的字符串:Hello World
```
2. 手动实现:
手动实现字符串联接可使用循环将第二个字符串的每一个字符逐一复制到第一个字符串的末尾,并在末尾添加结束符` `。
```c
#include
int main() {
char str1[100] = "Hello";
char str2[50] = " World";
int i, j;
i = 0;
while (str1[i] != ' ') {
i++;
}
j = 0;
while (str2[j] != ' ') {
str1[i] = str2[j];
i++;
j++;
}
str1[i] = ' ';
printf("连接后的字符串:%s
", str1);
return 0;
}
```
输出结果一样为:
```
连接后的字符串:Hello World
```
TOP