自定义实现字符串连接函数,用C++
时间: 2024-02-17 13:04:01 浏览: 81
好的,以下是一个简单的字符串连接函数的C++实现:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
char* string_concat(const char* str1, const char* str2)
{
int len1 = strlen(str1);
int len2 = strlen(str2);
char* result = new char[len1 + len2 + 1];
strcpy(result, str1);
strcat(result, str2);
return result;
}
int main()
{
const char* str1 = "hello";
const char* str2 = "world";
char* result = string_concat(str1, str2);
cout << result << endl;
delete[] result;
result = nullptr;
return 0;
}
```
这个函数的作用是将两个字符串连接起来。首先,我们通过 `strlen` 函数求出两个字符串的长度,然后通过 `new` 关键字在堆上动态分配一个字符数组,大小为两个字符串的长度之和加一(加一是为了给字符串末尾添加一个空字符)。接着,我们使用 `strcpy` 函数将第一个字符串复制到新字符数组中,再使用 `strcat` 函数将第二个字符串追加到新字符数组的末尾。最后,我们返回新字符串的指针,并在函数调用结束后记得释放内存。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.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)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.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)