簡體   English   中英

使用遞歸函數計算字符串中的元音

[英]count vowels in a string with recursion function

我目前在信息系統理學學士學位的最后一年,主修編程。 我參加並通過了C ++編程1。我現在在C ++編程2中,對遞歸函數有麻煩。 我們有一個家庭作業,假設我們要編寫一個程序,該程序將計算用戶輸入的字符串中的元音數量。 我的C ++編程1類有一個與此類似的程序,該程序使用for循環和if-then語句工作。 我以為將這個工作程序轉換為使用遞歸函數會很容易,我錯了。 我有代碼(不找人為我做),我認為我的設置正確。 只是不確定在函數中將調用放在何處。 有人可以指出正確的方向嗎?`這是我第一次問一個問題。 如果我的密碼錯誤,請通知我。

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

int vowelCount(string, int, int&);

int mail()
{
string input;
int len;
//int x;
//int y;
int count;

count = 0;

cout << "Enter a string of characters with no spaces: ";
cin >> input;
len = input.length();

vowelCount(input, len, count);

cout << "There were " << count << " vowels." << endl;

system("pause");
return 0;
}

int vowelCount(string input, int len, int& count)
{
int y;
int x;

y = input.at(len);
if (len == 1)
{
    count = count + 1;
    return count;
}
else
{
    y = input.at(len);
    if ((y == 'a') || (y == 'e') || (y == 'i') || (y == 'o') || (y == 'u')         || (y == 'A') || (y == 'E') || (y == 'I') || (y == 'O') || (y == 'U'))
    {
        count = count + 1;
        len = len - 1;
    }
        else
        {
            len = len - 1;
            vowelCount(string input, int len, int& count);
            return count;
        }
    }

}
return 0;
}

對於一般的理解,我建議對這個問題的答案。

首先,此代碼無法運行:它具有語法錯誤。 在擁有至少可以運行的程序之前,您不應該尋求邏輯幫助。 您不能使用整個簽名來調用函數。 對於實例,最后一塊應該很簡單

return vowelCount(input, len-1)

您將返回計數作為函數的值參數。 刪除參數。

現在,為了理解遞歸,請分兩步進行操作:

  1. 如果字符串為空,則返回0。
  2. 否則,請檢查當前字母:

2T(如果是元音),則返回1 + {其余字符串的計數}

2F else,返回{剩余字符串計數}

大括號中是您的兩個遞歸調用。 你能從這里拿走嗎?

我將通過以下方式編寫函數

#include <iostream>
#include <string>
#include <cstring>
#include <cctype>

std::string::size_type vowelCount( const std::string &input, std::string::size_type pos = 0 )
{
    const char *vowels = "AEIOU";
    return pos >= input.size() 
           ? 0 
           : ( std::strchr( vowels, std::toupper( ( unsigned char )input[pos] ) ) != nullptr ) 
             + vowelCount( input, pos + 1 );
}              


int main()
{
    std::string s;

    std::cin >> s;

    std::cout << "There were " << vowelCount( s ) << " vowels." << std::endl;

    return 0;
}

例如輸入

AaBbCcDdEe

那么輸出將是

There were 4 vowels.

我想該字符串不包含嵌入的零字符。:)否則,您應該替換條件

( std::strchr( vowels, std::toupper( ( unsigned char )input[pos] ) ) != nullptr ) 

對於

( input[pos] != '\0' && std::strchr( vowels, std::toupper( ( unsigned char )input[pos] ) ) != nullptr ) 

至於您的函數,那么如果在語法上將其編寫為有效,則由於例如以下語句而沒有意義

int vowelCount(string input, int len, int& count)
{
int y;
int x;

y = input.at(len);
^^^^^^^^^^^^^^^^^^

因為根據C ++標准成員函數at

5拋出:如果pos> = size(),則超出范圍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM