定义一个字符串类String。具体要求如下: (1)私有数据成员: char *ps; // 指向字符串的指针 int count[26]; //存放字符串中各字母(不分大小写)出现的次数,下标0对应于字母‘a’ (2)公有成员函数: String(); //缺省构造函数,不进行任何处理 String (char *p); // 构造函数,使用动态空间,并使ps指向参数;各字母出现的次数初始化为0 ~String(); // 析构函数。释放动态空间 void process(); // 统计字符串中各字母(不分大小写)出现的次数。 void show(); // 字符串中的内容,该字符串中字母出现的次数
时间: 2024-03-10 14:50:13 浏览: 172
好的,以下是实现 String 类的代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
class String {
private:
char *ps;
int count[26];
public:
String();
String(char *p);
~String();
void process();
void show();
};
String::String() {
ps = nullptr;
memset(count, 0, sizeof(count));
}
String::String(char *p) {
if (p != nullptr) {
int len = strlen(p);
ps = new char[len + 1];
strcpy(ps, p);
memset(count, 0, sizeof(count));
} else {
ps = nullptr;
memset(count, 0, sizeof(count));
}
}
String::~String() {
if (ps != nullptr) {
delete[] ps;
}
}
void String::process() {
if (ps != nullptr) {
int len = strlen(ps);
for (int i = 0; i < len; i++) {
if (ps[i] >= 'a' && ps[i] <= 'z') {
count[ps[i] - 'a']++;
} else if (ps[i] >= 'A' && ps[i] <= 'Z') {
count[ps[i] - 'A']++;
}
}
}
}
void String::show() {
if (ps != nullptr) {
cout << "The string is: " << ps << endl;
cout << "The count of each letter is:" << endl;
for (int i = 0; i < 26; i++) {
cout << char('a' + i) << ": " << count[i] << endl;
}
} else {
cout << "The string is empty." << endl;
}
}
int main() {
char str[] = "Hello, World!";
String s(str);
s.process();
s.show();
return 0;
}
```
该类包含一个指向字符串的指针和一个数组,用于存储字符串中各字母(不分大小写)出现的次数。构造函数中使用动态空间并初始化 count 数组为0;析构函数用于释放动态空间。process 函数用于统计字符串中各字母(不分大小写)出现的次数;show 函数用于输出字符串及各字母出现次数。在主函数中,定义了一个字符串并将其传入 String 类的构造函数中,然后调用 process 函数和 show 函数输出字符串及各字母出现次数。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.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)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)