设计一个String 类,完成以下任务
时间: 2024-03-02 17:49:36 浏览: 18
好的,以下是我设计的String类,它可以完成以下任务:
1. 通过构造函数初始化一个字符串对象
2. 通过成员函数获取字符串对象的长度
3. 通过成员函数获取字符串对象中指定位置的字符
4. 通过成员函数在字符串对象中查找指定字符,并返回其位置
5. 通过成员函数将字符串对象转换为大写或小写
6. 通过成员函数将两个字符串对象拼接在一起,并返回一个新的字符串对象
```c++
#include <iostream>
#include <cstring>
class String {
public:
String(const char* str) : m_str(nullptr) {
if (str != nullptr) {
m_str = new char[strlen(str) + 1];
strcpy(m_str, str);
}
}
~String() {
delete[] m_str;
}
int length() const {
return m_str ? strlen(m_str) : 0;
}
char at(int index) const {
if (m_str && index >= 0 && index < strlen(m_str)) {
return m_str[index];
}
return '\0';
}
int find(char c) const {
if (m_str) {
char* p = strchr(m_str, c);
if (p != nullptr) {
return p - m_str;
}
}
return -1;
}
void toUpperCase() {
if (m_str) {
int len = strlen(m_str);
for (int i = 0; i < len; i++) {
if (m_str[i] >= 'a' && m_str[i] <= 'z') {
m_str[i] -= 32;
}
}
}
}
void toLowerCase() {
if (m_str) {
int len = strlen(m_str);
for (int i = 0; i < len; i++) {
if (m_str[i] >= 'A' && m_str[i] <= 'Z') {
m_str[i] += 32;
}
}
}
}
String operator+(const String& other) const {
if (m_str == nullptr) {
return other;
}
if (other.m_str == nullptr) {
return *this;
}
char* temp = new char[strlen(m_str) + strlen(other.m_str) + 1];
strcpy(temp, m_str);
strcat(temp, other.m_str);
String result(temp);
delete[] temp;
return result;
}
private:
char* m_str;
};
```
使用示例:
```c++
String s1("Hello");
String s2("World");
String s3 = s1 + s2; // 拼接 s1 和 s2,得到 "HelloWorld"
std::cout << s3.length() << std::endl; // 输出 10
std::cout << s3.at(0) << std::endl; // 输出 'H'
std::cout << s3.find('W') << std::endl; // 输出 5
s3.toUpperCase(); // 转换为大写,得到 "HELLOWORLD"
s3.toLowerCase(); // 转换为小写,得到 "helloworld"
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)