#include <iostream>
#include <string>

using namespace std;

string expandString(int p1, int p2, int p3, string str) {
    string expandedStr;
    int n = str.length();

    for (int i = 0; i < n; i++) {
        if (str[i] == '-') {
            // 判断减号两边的字符是否满足展开条件
            if ((i > 0 && i < n - 1) && ((isdigit(str[i - 1]) && isdigit(str[i + 1])) || (islower(str[i - 1]) && islower(str[i + 1])))) {
                char left = str[i - 1];
                char right = str[i + 1];

                if (left < right) {
                    // 按照ASCII码顺序展开字符
                    for (char ch = left + 1; ch < right; ch++) {
                        if (p1 == 1) {
                            // 小写字母子串,填充小写字母
                            for (int j = 0; j < p2; j++) {
                                expandedStr += ch;
                            }
                        } else if (p1 == 2) {
                            // 小写字母子串,填充大写字母
                            for (int j = 0; j < p2; j++) {
                                expandedStr += toupper(ch);
                            }
                        } else if (p1 == 3) {
                            // 不论字母子串还是数字子串,填充星号
                            for (int j = 0; j < p2; j++) {
                                expandedStr += '*';
                            }
                        }
                    }
                } else if (left == right) {
                    // 相邻字符相等,只保留减号
                    expandedStr += '-';
                }
            } else {
                // 不满足展开条件,直接输出减号
                expandedStr += '-';
            }
        } else {
            // 非减号字符,直接输出
            expandedStr += str[i];
        }
    }

    // 根据p3参数判断是否逆序输出
    if (p3 == 2) {
        reverse(expandedStr.begin(), expandedStr.end());
    }

    return expandedStr;
}

int main() {
    int p1, p2, p3;
    string str;
    cin >> p1 >> p2 >> p3;
    cin.ignore();
    getline(cin, str);

    string expandedStr = expandString(p1, p2, p3, str);
    cout << expandedStr << endl;

    return 0;
}
C++字符串展开:巧用ASCII码与循环

原文地址: http://www.cveoy.top/t/topic/YIP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录