c++实现编一程序,将两个字符串连接起来。结果取代第一个字符串。要求 1、用字符数组,不用strcat 函数; 2、用C 标准中的strcat 函数; 3、用string 方法定义字符串变量; 4、对这三种方法进行比较。
时间: 2023-05-10 09:55:36 浏览: 83
1、用字符数组,不用strcat函数:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[] = "World";
int i, j;
// 找到str1的末尾位置
for (i = 0; str1[i] != '\0'; i++);
// 将str2连接到str1的末尾
for (j = 0; str2[j] != '\0'; j++, i++) {
str1[i] = str2[j];
}
// 添加字符串结束标志
str1[i] = '\0';
printf("连接后的字符串为:%s\n", str1);
return 0;
}
```
2、用C标准中的strcat函数:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[] = "World";
strcat(str1, str2);
printf("连接后的字符串为:%s\n", str1);
return 0;
}
```
3、用string方法定义字符串变量:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[] = "World";
char str3[20];
strcpy(str3, str1);
strcat(str3, str2);
printf("连接后的字符串为:%s\n", str3);
return 0;
}
```
4、对这三种方法进行比较:
第一种方法需要手动遍历字符串数组,比较繁琐,但是可以更好地理解字符串的本质。第二种方法使用了C标准库中的strcat函数,代码简洁,但是需要注意目标字符串的长度。第三种方法使用了string方法定义字符串变量,代码简洁易懂,但是需要注意字符串数组的长度。总的来说,三种方法各有优缺点,需要根据具体情况选择适合的方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)