用c++设计一个字符串类(MyString),除具有一般的输入输出字符串的功能外,还要求具有计算字符串长度,连接两个字符串的功能。
时间: 2023-06-17 20:02:17 浏览: 70
以下是一个简单的 MyString 类的实现,包括字符串长度计算、字符串连接和输入输出字符串的功能:
```c++
#include <iostream>
#include <cstring>
class MyString {
private:
char* str;
public:
MyString() : str(nullptr) {} // 默认构造函数
MyString(const char* s); // 构造函数
MyString(const MyString& other); // 拷贝构造函数
~MyString(); // 析构函数
int length() const; // 计算字符串长度
void concat(const MyString& other); // 连接两个字符串
friend std::ostream& operator<<(std::ostream& os, const MyString& mystr); // 输出字符串
friend std::istream& operator>>(std::istream& is, MyString& mystr); // 输入字符串
};
MyString::MyString(const char* s) {
if (s != nullptr) {
str = new char[strlen(s) + 1];
strcpy(str, s);
} else {
str = nullptr;
}
}
MyString::MyString(const MyString& other) {
if (other.str != nullptr) {
str = new char[strlen(other.str) + 1];
strcpy(str, other.str);
} else {
str = nullptr;
}
}
MyString::~MyString() {
if (str != nullptr) {
delete[] str;
}
}
int MyString::length() const {
if (str != nullptr) {
return strlen(str);
} else {
return 0;
}
}
void MyString::concat(const MyString& other) {
if (other.str != nullptr) {
int len1 = length();
int len2 = other.length();
char* tmp = new char[len1 + len2 + 1];
strcpy(tmp, str);
strcat(tmp, other.str);
if (str != nullptr) {
delete[] str;
}
str = tmp;
}
}
std::ostream& operator<<(std::ostream& os, const MyString& mystr) {
if (mystr.str != nullptr) {
os << mystr.str;
}
return os;
}
std::istream& operator>>(std::istream& is, MyString& mystr) {
char buf[1024];
is.getline(buf, 1024);
if (mystr.str != nullptr) {
delete[] mystr.str;
}
mystr.str = new char[strlen(buf) + 1];
strcpy(mystr.str, buf);
return is;
}
```
使用示例:
```c++
int main() {
MyString s1("Hello");
MyString s2(" world!");
std::cout << s1 << std::endl; // 输出 "Hello"
std::cout << s2 << std::endl; // 输出 " world!"
s1.concat(s2);
std::cout << s1 << std::endl; // 输出 "Hello world!"
std::cout << "Length of s1: " << s1.length() << std::endl; // 输出 "Length of s1: 12"
MyString s3;
std::cout << "Input a string: ";
std::cin >> s3;
std::cout << "You input: " << s3 << std::endl;
return 0;
}
```