C++ Krunch 操作:去除句子中所有元音字母
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
C++ 代码实现
#include<iostream>
#include<string>
using namespace std;
bool isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
}
int main() {
string sentence;
getline(cin, sentence);
string result = "";
string word = "";
for (int i = 0; i < sentence.length(); i++) {
if (sentence[i] == ' ' || sentence[i] == '.' || sentence[i] == '?' || sentence[i] == '!') {
if (word.empty()) {
result += sentence[i];
} else {
bool allVowels = true;
for (int j = 0; j < word.length(); j++) {
if (!isVowel(word[j])) {
allVowels = false;
break;
}
}
if (allVowels) {
result += ' ';
} else {
result += word;
}
result += sentence[i];
word = "";
}
} else {
word += sentence[i];
}
}
cout << result << endl;
return 0;
}
代码中,我们首先定义了一个名为 isVowel 的函数,用于判断一个字符是否为元音字母。然后,在 main 函数中,我们使用 getline 函数读取输入的句子,并使用两个字符串变量 result 和 word 来存储 Krunch 操作后的结果和当前正在处理的单词。我们遍历输入的句子,逐个字符判断是否为元音字母、空格或标点符号,并根据情况对 result 和 word 进行相应操作。最后,我们输出 result 的内容,即 Krunch 操作后的句子。
**代码说明:**
- 代码中使用了
getline函数来读取输入的句子,因为句子可能包含空格。 - 代码中使用了
isVowel函数来判断一个字符是否为元音字母,以便在 Krunch 操作中进行处理。 - 代码中使用了两个字符串变量
result和word来存储 Krunch 操作后的结果和当前正在处理的单词,以便于对每个单词进行单独的处理。 - 代码中使用了
if和else语句来判断当前字符的类型,并根据情况对result和word进行相应操作。
通过以上步骤,我们可以实现对输入的句子进行 Krunch 操作,并将结果输出到控制台。
原文地址: https://www.cveoy.top/t/topic/pXLU 著作权归作者所有。请勿转载和采集!