簡體   English   中英

如何在遞歸函數中返回某個布爾值?

[英]How to return a certain boolean value in a recursive function?

我想做一個遞歸函數,確定一個字符串的字符是否全部由字母組成。 我只是想不通。 這是我到目前為止所做的,但無法正常工作。

bool isAlphabetic(string s){
const char *c = s.c_str();
if ((!isalpha(c[0]))||(!isalpha(c[s.size()])))
{
    return false;
}
else if (isalpha(c[0]))
{
    isAlphabetic(c+1);
    return true;
}
}

誰能提出正確的方法?

撇開您將要創建的許多部分字符串(考慮只傳遞字符串和起始索引), isalpha(c[s.size()])檢查將始終失敗,因為這是\\0結尾字符串。 您還忽略了遞歸調用的結果。

bool isAlphabetic(string s){
  if (s.size() < 1)
    return true;               // empty string contains no non-alphas

  const char *c = s.c_str();

  if (!isalpha(c[0]))
  {
    return false;              // found a non-alpha, we're done.
  }
  else
  {
    return isAlphabetic(c+1);  // good so far, try the rest of the string
  }
}

Paul的答案為基礎 ,這是一個固定的實現,不會復制字符串的任何部分。 它通過傳遞對string對象的引用和對要檢查的字符的索引來實現此目的; 遞歸只是向該索引加1以檢查下一個字符,依此類推,直到找到字符串的結尾。

我已經刪除了您對c_str()調用,因為它不是必需的。 string可以直接索引。

bool isAlphabetic(string const & s, int startIndex = 0) {
    // Terminating case: End of string reached. This means success.
    if (startIndex == s.size()) {
        return true;
    }

    // Failure case: Found a non-alphabetic character.
    if (!isalpha(s[startIndex])) {
        return false;
    }

    // Recursive case: This character is alphabetic, so check the rest of the string.
    return isAlphabetic(s, startIndex + 1);
}

請注意,此功能將空字符串視為字母。 您可以通過將return true更改為return !s.empty()來進行更改。

這是一個工作示例:

#include <iostream>
#include <string>

using namespace std;

bool isAlphabetic(string s)
{
    if( s.empty() )
    {
        return false;
    }

    cout << "checking: " << s[0] << endl;

    if( isalpha(s[0]) )
    {
        return true;
    }

    return isAlphabetic(&s[0]+1);
}

int main()
{
    string word0 = "test";
    if( isAlphabetic(word0) )
    {
        cout << word0 << " is alphabetic" << endl; 
    }
    else
    {
        cout << word0 << " is NOT alphabetic" << endl; 
    }

    string word1 = "1234";
    if( isAlphabetic(word1) )
    {
        cout << word1 << " is alphabetic" << endl; 
    }
    else
    {
        cout << word1 << " is NOT alphabetic" << endl; 
    }

    string word2 = "1234w";
    if( isAlphabetic(word2) )
    {
        cout << word2 << " is alphabetic" << endl; 
    }
    else
    {
        cout << word2 << " is NOT alphabetic" << endl; 
    }

   return 0;
}

暫無
暫無

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

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