定义一个字符串类str,该类中包含2个属性,字符串长度和一个char型指针保存字符串内容。增加以下运算符的重载:+、- 。+运算符表示把2个字符串拼接成一个字符串。-运算符表示例如a2-a1,则删除a2中出现的a1字符串。 要求如下: 1.实现str类; 2.编写main函数,初始化2个str对象A、B,输出这2个对象相加后的对象C的结果信息。输出C与B之间相减后的结果信息。 (提示:strstr(char *a,char*b)可以从a字符串中查找出b首次出现的地址) 输入 第1行:输入一个字符串,初始化第一个str对象。 (提示:通过cin. getline(char *,int strCount)可以输入一个字符串到char数组中) 第2行:输入一个字符串,初始化第二个str对象。 输出 第1行:输出两个字符串相加后的长度和字符串。 第2行:输出两个字符串相减后的长度和字符串。
时间: 2023-11-28 22:47:16 浏览: 35
下面是一种可能的实现方式:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
class str {
public:
str() : len(0), content(NULL) {}
str(const char* s) {
len = strlen(s);
content = new char[len + 1];
strcpy(content, s);
}
str(const str& other) {
len = other.len;
content = new char[len + 1];
strcpy(content, other.content);
}
~str() {
if (content) {
delete[] content;
}
}
str operator+(const str& other) const {
str result;
result.len = len + other.len;
result.content = new char[result.len + 1];
strcpy(result.content, content);
strcat(result.content, other.content);
return result;
}
str operator-(const str& other) const {
str result(*this);
char* p = strstr(result.content, other.content);
if (p) {
strcpy(p, p + other.len);
result.len -= other.len;
}
return result;
}
friend ostream& operator<<(ostream& os, const str& s) {
os << "length: " << s.len << ", content: " << s.content;
return os;
}
private:
int len;
char* content;
};
int main() {
char s1[100], s2[100];
cin.getline(s1, 100);
cin.getline(s2, 100);
str A(s1), B(s2);
str C = A + B;
cout << C << endl;
str D = C - B;
cout << D << endl;
return 0;
}
```
输入两个字符串,分别转化为str对象A和B,然后可以直接使用运算符重载实现字符串的拼接和删除操作,得到结果对象C和D,并输出它们的长度和内容。注意在输出时,要重载输出流运算符<<。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)