1 Star 0 Fork 0

Admin / text_cpp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
string.cpp 3.05 KB
一键复制 编辑 原始数据 按行查看 历史
Admin 提交于 2024-05-08 16:57 . 字符串类(1)
#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;
}
1
https://gitee.com/small-c_2_0/text_cpp.git
git@gitee.com:small-c_2_0/text_cpp.git
small-c_2_0
text_cpp
text_cpp
master

搜索帮助