檢查所有子字串的母音數量是否至少與子音數量相同


在字母序列中,包含 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(),在需要時滿足了特定需求。此型別通常用於解決演算法問題陳述。

更新於: 2023-08-16

161 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告