【问题标题】:How to convert this code to use string如何将此代码转换为使用字符串
【发布时间】:2011-04-17 02:29:21
【问题描述】:
char * recursivecombo(char *str, int choices, int level)
{
    int len = strlen(str);

    level++;
    if( level == choices)
    {   
            for (int i = 0; i < len -2; i++)

            {   

                   printf("%c", str[i]) ;
            }   
    }   
    else
    {   
        for (int i = 0; i < len - 2; i++)
        {   
                printf("%c",str[i]);
                recursivecombo(str.substr(1), level);

        }   
    }   
}

我想使用字符串而不是 char*。

【问题讨论】:

  • 如何在 char* 上执行此 str.substr(1) ?而且,您不会从此函数返回任何内容。在 Java 中这是不可编译的,我不确定 C++ 是如何处理这个的,但我至少会假设一些错误。
  • 为什么要使用字符串?它是否比这段代码更好(更快、更小、可读、可移植)?
  • 除了上面提出的问题之外,您的代码将无法编译,因为您的递归调用没有足够的参数。
  • 如果你修复你当前的代码,让它工作并且可以编译它会更容易帮助转换和改变它。
  • 如果 str 是一个字符串,那么 str.substr 应该返回一个字符串。

标签: c++ string char


【解决方案1】:
std::string recursivecombo(const std::string& str, int choices, int level)
{
    level++;
    for (int i = 0; i < str.length() -2; ++i)
    {
        cout<<str.at(i) ;
        if( level != choices)
            recursivecombo(str.substr(1),8,/*Missing choce*/ level);
    }  
/*Missing return value*/ 
}

这只是一个使用字符串的模型。您的功能存在一些问题

1)你的返回值在哪里

2)如果你打算使用字符串使用cout,而不是printf,如果它是C++

3)使用前缀++。

【讨论】:

  • 很好地使用了at(i)。请注意,i2 将在 i&lt;str.length()-2 中提升为 unsigned long,因此循环可能永远不会终止(或很长时间不会终止)。
【解决方案2】:

正如其他人发布的那样,您没有记录退货,因此这将是等效代码:

string recursivecombo(const std::string & str, int choices, int level)
{
     what I wouldn't give for a holocaust cloak
}

我想你的意思可能是:

void recursivecombo(const std::string & strInput, int nChoices, int nLevel = 0);

实现为:

void recursivecombo(const string & strInput, int nChoices, int nLevel /* = 0 */)
{
    nLevel++;
    if( nLevel == nChoices ) cout << strInput.substr(0,strInput.length()-2);
    else
    {
        for ( int i = 0; i < str.length() - 2; i++)
        {
            cout << str.at(i);
            recursivecombo(str.substr(1), nChoice, nLevel);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2014-10-08
    • 2017-09-16
    • 1970-01-01
    • 2011-12-06
    • 2018-11-13
    • 2020-09-20
    • 1970-01-01
    • 2015-12-11
    相关资源
    最近更新 更多