C++ 检查所有子字符串中元音字母数量至少与辅音字母数量相同
在字母序列中,有26个字符,其中5个字符是元音字母,如a、e、i、o、u,其余的称为辅音字母。在C++中,我们有预定义的函数,如tolower()和length(),可以帮助检查所有子字符串中元音字母数量至少与辅音字母数量相同。
让我们以一个例子来说明。
- 字符串只有一个辅音字母和其他都是元音字母 “aiteau” 。因此,它被接受为最终结果。
-
字符串中有一个以上的辅音字母和其他都是元音字母 “appioa” 。因此,它不被接受为最终结果。
使用简单for循环
该程序使用基于元音字母和至少辅音字母的两个函数定义。这些函数提供了一些循环和运算符,有助于解决这个问题。
语法
以下语法用于示例:
tolower()
预定义函数 tolower() 将任何给定的字符转换为小写。
length()
length()是C++中的预定义函数,用于找到给定字符串的长度。
步骤
以下步骤是:
步骤1:通过包含头文件iostream来启动程序。
步骤2:然后使用函数定义vowel_letter(),该函数用于设置内置函数tolower()以将字符转换为小写。然后通过使用操作符和||指定带有元音字符的函数来返回函数。
步骤3:接下来,它将定义另一个名为atleast_consonant()的函数定义,该函数接受参数str以获取给定字符串的输入。此函数用于在一个辅音字母和其余元音字母上工作。例如- aatuuie:t只是一个辅音字母,其余的字母是元音字母。
步骤4:然后使用第一个for循环,变量i迭代输入字符串,并使用一些操作符(例如!和&&)在if语句的条件中连接以工作函数定义vowel_letter。如果在给定字符串中找到超过一个辅音字母,则返回false。
步骤5:继续使用第二个for循环,其中将使用if语句来设置基于&&操作符的条件。如果元音周围有多个辅音字母,则如果所有条件都满足,则返回false,否则返回true。
步骤6:现在开始程序的主函数并初始化输入字符串。
步骤7:使用if-else语句,将条件设为调用函数,并传递字符串的输入,以检查是否至少存在辅音字母。
示例
在下面的示例中,我们将使用两个for循环,其中第一个循环根据当前给定列表中的一个连续辅音字母字符进行迭代,而第二个循环将根据被多个辅音字母包围的元音进行使用,以验证此问题。
#include <iostream>
using namespace std;
// function operate to work on vowel character
bool vowel_letter(char ch)
{
// Using tolower() covert the character into a lowercase letter
ch = tolower(ch);
// Set the condition to check the character vowel by using the operator logical OR and equal to
return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
}
// function operate to work on at least one consonant character present with the rest vowel.
bool atleast_consonant(const string& str)
{
int n = str.length();
// Using the first iteration it checks if more than one consecutive consonant present
for (int i = 1; i < n; i++)
{
if (!vowel_letter(str[i]) && !vowel_letter(str[i - 1]))
return false;
}
// Using the second iteration it checks if the vowel is surrounded by more than one consonant
for (int i = 1; i < n - 1; i++)
{
if (vowel_letter(str[i]) && !vowel_letter(str[i - 1]) && !vowel_letter(str[i + 1]))
return false;
}
// return true when there exists only one consonant with vowels
return true;
}
// Start the main function
int main()
{
string stng = "abaue";
// Function call used under if-statement
if (atleast_consonant(stng))
cout << "The given problem statement is satisfied." << endl;
else
cout << "The given problem statement is not satisfied" << endl;
return 0;
}
输出
The given problem statement is satisfied.
结论
元音和辅音是字母表中的字符,并且可以在程序活动中用于解决特定问题。当需要时,使用了一些预定义的函数,例如tolower()和length(),以满足特定需求。这种类型通常用于解决算法性的问题陈述。