用返回指针类型函数实现字符串连接函数strcat(),通过 ⑴输入字符串s1和s2进行测试。 ⑵将字符串“string”作为参数与s1和s2的连接后的结果调用函数strcat()实现连接。
时间: 2024-02-26 19:59:10 浏览: 61
好的,可以通过以下代码实现:
```c++
#include <iostream>
#include <cstring>
using namespace std;
char* my_strcat(char* s1, char* s2) {
int len1 = strlen(s1);
int len2 = strlen(s2);
char* result = new char[len1+len2+1]; // 分配内存
strcpy(result, s1); // 复制s1
strcpy(result+len1, s2); // 复制s2
return result;
}
int main() {
char s1[20] = "Hello";
char s2[20] = "world";
char* result = my_strcat(s1, s2);
cout << result << endl; // 输出"Helloworld"
delete[] result; // 释放内存
result = my_strcat(s1, "string");
cout << result << endl; // 输出"Helloworldstring"
delete[] result; // 释放内存
return 0;
}
```
在my_strcat函数中,我们首先获取s1和s2的长度,然后分配内存空间,将s1和s2复制到结果字符串中,最后返回指向结果字符串的指针。在主函数中,我们测试了两种情况:先将s1和s2连接,再将"string"与连接结果连接。
阅读全文
相关推荐

















