完成 MyString 类的实现 class MyString { public: // 将这个MyString对象与另一个MyString对象相连 MyString& operator+=(const MyString &s); // 返回下标为pos的字符 char& operator[](int pos); // 返回子串 [pos, pos+count) // 若请求的子串越过字符串的结尾,即count大于size() - pos,则返回的子串为[pos, size()) // 若pos不在字符串的下标范围内,返回空的MyString对象 // 若count == -1,返回子串[pos, size()) MyString substr(int pos = 0, int count = -1); // 字符串的长度 int size() const; // 返回C语言风格的字符串 const char* c_str() const; private: char *m_buf; int m_size; };
时间: 2024-03-23 19:40:38 浏览: 97
C++ MyString 类
下面是 MyString 类的实现代码:
```cpp
class MyString {
public:
MyString() : m_buf(nullptr), m_size(0) {} // 默认构造函数
MyString(const char* str) { // 带参构造函数
m_size = strlen(str);
m_buf = new char[m_size + 1];
strcpy(m_buf, str);
}
MyString(const MyString& other) { // 拷贝构造函数
m_size = other.m_size;
m_buf = new char[m_size + 1];
strcpy(m_buf, other.m_buf);
}
~MyString() { // 析构函数
delete[] m_buf;
}
MyString& operator+=(const MyString& s) { // 字符串拼接
int new_size = m_size + s.m_size;
char* new_buf = new char[new_size + 1];
strcpy(new_buf, m_buf);
strcat(new_buf, s.m_buf);
delete[] m_buf;
m_buf = new_buf;
m_size = new_size;
return *this;
}
char& operator[](int pos) { // 下标运算符
if (pos < 0 || pos >= m_size) {
throw "Out of range!";
}
return m_buf[pos];
}
MyString substr(int pos = 0, int count = -1) { // 子串
if (pos < 0 || pos >= m_size) {
return MyString();
}
if (count == -1) {
count = m_size - pos;
}
if (pos + count > m_size) {
count = m_size - pos;
}
char* new_buf = new char[count + 1];
strncpy(new_buf, m_buf + pos, count);
new_buf[count] = '\0';
MyString res(new_buf);
delete[] new_buf;
return res;
}
int size() const { // 长度
return m_size;
}
const char* c_str() const { // C 语言风格的字符串
return m_buf;
}
private:
char* m_buf;
int m_size;
};
```
使用示例:
```cpp
MyString s1("Hello, ");
MyString s2("world!");
s1 += s2;
std::cout << s1.c_str() << std::endl; // 输出 "Hello, world!"
MyString s3("abcdefg");
std::cout << s3[2] << std::endl; // 输出 'c'
MyString s4("0123456789");
MyString s5 = s4.substr(2, 5);
std::cout << s5.c_str() << std::endl; // 输出 "23456"
```
阅读全文