C++ Krunch 操作 - 移除单词元音字母

题目描述:

Krunch 是一种对单词的操作,Krunch 一个单词其实就是把该单词中所有的元音字母 (aeiou) 去除,不管它是大写还是小写。

编写一个程序,对一个句子进行 Krunch 操作。需要注意的是:如果一个单词完全由元音字母组成,Krunch 后它将化为乌有,这时你需要去掉多余的空格使它看上去仍像一个句子。

输入:

一个不超过 72 个字符的句子,标点后没有元音字母。

输出:

Krunch 操作后得到的句子。

样例输入 1:

Krunch a bunch of munchies for lunch.

样例输出 1:

Krnch bnch f mnchs fr lnch.

**时间限制:**1.0Sec **内存限制:**128MB

代码:

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

bool isVowel(char c) {
    c = tolower(c);
    return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}

string krunch(string sentence) {
    string result = '';
    bool isWord = false;
    for (int i = 0; i < sentence.length(); i++) {
        if (isalpha(sentence[i])) {
            if (!isWord) {
                result += ' ';
            }
            isWord = true;
            if (!isVowel(sentence[i])) {
                result += sentence[i];
            }
        } else {
            result += sentence[i];
            isWord = false;
        }
    }
    if (result[0] == ' ') {
        result = result.substr(1);
    }
    if (result[result.length() - 1] == ' ') {
        result = result.substr(0, result.length() - 1);
    }
    return result;
}

int main() {
    string sentence;
    getline(cin, sentence);
    cout << krunch(sentence) << endl;
    return 0;
}

代码说明:

  1. **isVowel(char c) 函数:**用于判断字符 c 是否为元音字母(不区分大小写)。
  2. krunch(string sentence) 函数:
    • 初始化一个空字符串 result 用于存储 Krunch 后的结果。
    • 使用 isWord 变量记录当前字符是否在一个单词中,初始值为 false
    • 遍历句子中的每个字符:
      • 如果字符是字母:
        • 如果当前不是在一个单词中,则在 result 中添加空格。
        • isWord 设置为 true,表示当前字符在一个单词中。
        • 如果字符不是元音字母,则将字符添加到 result 中。
      • 如果字符不是字母(即空格或标点符号),则直接将字符添加到 result 中,并将 isWord 设置为 false
    • 最后,检查 result 的第一个和最后一个字符是否为空格,如果为空格则将其移除。
  3. main() 函数:
    • 从标准输入读取一行字符串(句子),存储到 sentence 变量中。
    • 调用 krunch() 函数对句子进行 Krunch 操作,并将结果输出到标准输出。
C++ Krunch 操作 - 移除单词元音字母

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

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