代码拉取完成,页面将自动刷新
#include <iostream>
#include <cstring>
class String {
private:
char* str; // 字符串指针
int length; // 字符串长度
public:
// 默认构造函数
String() : str(nullptr), length(0) {}
// 构造函数
String(const char* s) {
length = strlen(s);
str = new char[length + 1];
strcpy(str, s);
}
// 拷贝构造函数
String(const String& other) {
length = other.length;
str = new char[length + 1];
strcpy(str, other.str);
}
// 析构函数
~String() {
delete[] str;
}
// 获取字符串长度
int getLength() const {
return length;
}
// 获取字符串内容
const char* getStr() const {
return str;
}
// 根据下标读取字符
char& operator[](int index) {
return str[index];
}
// 根据下标读取字符(常量对象)
const char& operator[](int index) const {
return str[index];
}
// 字符串赋值拷贝
String& operator=(const String& other) {
if (this != &other) {
delete[] str;
length = other.length;
str = new char[length + 1];
strcpy(str, other.str);
}
return *this;
}
// 字符串拼接
String operator+(const String& other) const {
String result;
result.length = length + other.length;
result.str = new char[result.length + 1];
strcpy(result.str, str);
strcat(result.str, other.str);
return result;
}
// 字符串比较
bool operator==(const String& other) const {
return strcmp(str, other.str) == 0;
}
// 求子串
String substr(int start, int len) const {
String result;
result.length = len;
result.str = new char[len + 1];
strncpy(result.str, str + start, len);
result.str[len] = '\0';
return result;
}
// 查找子串
int find(const String& sub) const {
const char* ptr = strstr(str, sub.str);
if (ptr == nullptr) {
return -1; // 找不到子串
}
else {
return ptr - str; // 返回子串在原字符串中的起始位置
}
}
};
int main() {
String s1("Hello");
String s2("World");
// 测试初始化、长度、读取操作
std::cout << "s1: " << s1.getStr() << ", Length: " << s1.getLength() << std::endl;
std::cout << "s2: " << s2.getStr() << ", Length: " << s2.getLength() << std::endl;
// 测试赋值拷贝
String s3 = s1;
std::cout << "Copy of s1: " << s3.getStr() << std::endl;
// 测试拼接
String s4 = s1 + s2;
std::cout << "Concatenated string: " << s4.getStr() << std::endl;
// 测试比较
std::cout << "s1 == s2: " << (s1 == s2) << std::endl;
std::cout << "s1 == s3: " << (s1 == s3) << std::endl;
// 测试子串
String sub = s4.substr(3, 5);
std::cout << "Sub-string: " << sub.getStr() << std::endl;
// 测试查找子串
int pos = s4.find(sub);
if (pos != -1) {
std::cout << "Substring found at position: " << pos << std::endl;
}
else {
std::cout << "Substring not found." << std::endl;
}
return 0;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。