请c++编写一个程序,该程序包含两个类,分别存放输入的字符串中的数字和字母,并按各自的顺序排列,类中实现一个dump函数,调用后输出类中当前存放的字符串结果
#include <iostream>
#include <string>
using namespace std;
// 简单的冒泡排序函数
void bubbleSort(string& str) {
int n = str.length();
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (str[j] > str[j + 1]) {
// 交换 str[j] 和 str[j + 1]
swap(str[j], str[j + 1]);
}
}
}
}
// 检查字符是否为数字
bool isDigit(char c) {
return c >= '0' && c <= '9';
}
// 检查字符是否为字母
bool isLetter(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
class Collector {
public:
virtual void addChar(char c) = 0;
virtual void dump() const = 0;
};
class NumberCollector : public Collector {
private:
string numbers;
public:
void addChar(char c) override {
if (isDigit(c)) {
numbers += c;
}
}
void sortAndDump() {
bubbleSort(numbers);
dump();
}
void dump() const override {
cout << "Numbers: " << numbers << endl;
}
};
class LetterCollector : public Collector {
private:
string letters;
public:
void addChar(char c) override {
if (isLetter(c)) {
letters +=tolower(c); // 转换为小写
}
}
void sortAndDump() {
bubbleSort(letters);
dump();
}
void dump() const override {
cout << "Letters: " << letters << endl;
}
};
int main() {
string input;
cout << "Enter a string: ";
getline(cin, input);
NumberCollector numberCollector;
LetterCollector letterCollector;
for (char c : input) {
numberCollector.addChar(c);
letterCollector.addChar(c);
}
numberCollector.sortAndDump();
letterCollector.sortAndDump();
return 0;
}