请定义一个 `MyString` 类,提供一些常见的字符串操作方法,例如字符串拼接、判断字符串相等、截取子字符串、获取字符串长度以及显示字符串等。这些方法可以通过重载运算符和调用 `string` 类的成员函数来实现。在 `main` 函数中,创建了几个 `MyString` 对象并进行了一些操作,请编程实现MyString类,使得下面main测试程序能得到正确结果。 int main() { MyString s1("Hello"); MyString s2(" World"); MyString s3 = s1 + s2; // 拼接字符串 s3.print(); if (s1 == s2) { // 判断字符串相等 cout << "s1 equals to s2" << endl; } else { cout << "s1 is not equal to s2" << endl; } MyString sub = s3.substring(6, 5); // 截取子字符串 sub.print(); //显示字符串 cout << "Length of s3: " << s3.length() << endl; // 字符串长度 return 0; }
时间: 2024-01-24 19:05:43 浏览: 71
C++类的封装之 字符串MyString类
实现一个 `MyString` 类的代码如下:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
class MyString {
private:
char* str;
public:
MyString(const char* s = "") {
str = new char[strlen(s) + 1];
strcpy(str, s);
}
MyString(const MyString& other) {
str = new char[strlen(other.str) + 1];
strcpy(str, other.str);
}
~MyString() {
delete[] str;
}
MyString operator+(const MyString& other) const {
MyString result;
result.str = new char[strlen(str) + strlen(other.str) + 1];
strcpy(result.str, str);
strcat(result.str, other.str);
return result;
}
bool operator==(const MyString& other) const {
return strcmp(str, other.str) == 0;
}
MyString substring(int start, int length) const {
MyString result;
result.str = new char[length + 1];
strncpy(result.str, str + start, length);
result.str[length] = '\0';
return result;
}
int length() const {
return strlen(str);
}
void print() const {
cout << str << endl;
}
};
```
在 `main` 函数中,我们可以测试 `MyString` 类的各种方法:
```cpp
int main() {
MyString s1("Hello");
MyString s2(" World");
MyString s3 = s1 + s2; // 拼接字符串
s3.print();
if (s1 == s2) { // 判断字符串相等
cout << "s1 equals to s2" << endl;
} else {
cout << "s1 is not equal to s2" << endl;
}
MyString sub = s3.substring(6, 5); // 截取子字符串
sub.print(); //显示字符串
cout << "Length of s3: " << s3.length() << endl; // 字符串长度
return 0;
}
```
输出结果:
```
Hello World
s1 is not equal to s2
World
Length of s3: 11
```
阅读全文