c++string类的模拟实现:插入字符/字符串
作者:野牛程序员:2024-01-03 14:30:54 C++阅读 2387
C++中的字符串类模拟实现可以包括插入字符和字符串的功能。下面是一个简单的模拟实现示例,其中包括插入字符和字符串的操作:
#include <iostream> class MyString { private: char* data; size_t length; size_t capacity; public: // 构造函数 MyString() : data(nullptr), length(0), capacity(0) {} // 析构函数 ~MyString() { if (data != nullptr) { delete[] data; } } // 插入单个字符 void insertChar(char ch, size_t position) { if (position > length) { std::cerr << "Invalid position for insertion." << std::endl; return; } if (length + 1 > capacity) { // 扩展容量 capacity = (capacity == 0) ? 1 : capacity * 2; char* newData = new char[capacity]; // 复制已有数据 for (size_t i = 0; i < position; ++i) { newData[i] = data[i]; } // 插入新字符 newData[position] = ch; // 复制剩余数据 for (size_t i = position; i < length; ++i) { newData[i + 1] = data[i]; } // 释放旧数据并更新指针 delete[] data; data = newData; ++length; } else { // 直接插入字符 for (size_t i = length; i > position; --i) { data[i] = data[i - 1]; } data[position] = ch; ++length; } } // 插入字符串 void insertString(const char* str, size_t position) { size_t strLength = strlen(str); if (position > length) { std::cerr << "Invalid position for insertion." << std::endl; return; } if (length + strLength > capacity) { // 扩展容量 capacity = (capacity == 0) ? strLength : capacity * 2; char* newData = new char[capacity]; // 复制已有数据 for (size_t i = 0; i < position; ++i) { newData[i] = data[i]; } // 插入新字符串 for (size_t i = 0; i < strLength; ++i) { newData[position + i] = str[i]; } // 复制剩余数据 for (size_t i = position; i < length; ++i) { newData[position + strLength + i] = data[i]; } // 释放旧数据并更新指针和长度 delete[] data; data = newData; length += strLength; } else { // 直接插入字符串 for (size_t i = length; i > position; --i) { data[i + strLength - 1] = data[i - 1]; } for (size_t i = 0; i < strLength; ++i) { data[position + i] = str[i]; } length += strLength; } } // 输出字符串 void print() const { for (size_t i = 0; i < length; ++i) { std::cout << data[i]; } std::cout << std::endl; } }; int main() { MyString myString; // 插入单个字符 myString.insertChar('H', 0); myString.insertChar('i', 1); // 输出结果: Hi myString.print(); // 插入字符串 myString.insertString(" there", 2); // 输出结果: Hi there myString.print(); return 0; }
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892