【问题标题】:Recursive version of strlen in c Strings c++c字符串中strlen的递归版本c ++
【发布时间】:2020-03-23 04:06:57
【问题描述】:

我正在为我的第一个 c++ 课程的作业而苦苦挣扎。我希望有人可以在正确的方向上帮助我。我需要在 c 字符串中编写一个“strlen 的递归版本”。根据我的讲义,我的函数应该是这样的,“int str_length(char s[])”。

我的主要问题是试图让用户输入一个长度不确定的字符串或 cstring 并将其用于函数调用。我真的很感激我能得到的所有帮助和指导。

我已经玩了很多次我的代码,以至于我迷失了方向。看来我会解决一个问题并创建一个新问题。我认为我的函数编写正确,但如果有更好/正确的方法,这里是代码。

#include <iostream>
#include <cstring> //included both until I find my solution
#include <string>
using namespace std;


//string or char sentence;  This part of my struggle
char choice = 'Y';
int str_length(char s[]);


int main()
{

    while ((choice != 'n') && (choice != 'N'))
    {

        cout << "Enter a sentence. ";
        //user entry cin, getline etc
        cout << sentence;
        //cout << str_length(sentence);
        cout << endl;

        cout << "Do you want to have another run? Y/N ";
        cin >> choice; 
    }

}



int str_length(char s[])
{
    // if we reach at the end of the string 
    if (s == '\0')
    {
        return 0;
    }
    else
    {
        return 1 + str_length(s + 1);
    }
}

【问题讨论】:

  • 当代码按预期工作时,为什么你还在苦苦挣扎?有什么问题?
  • 你是在问std::getline()怎么用?
  • 是您得到“错误”长度的问题,例如“这是一个包含多个单独单词的句子,cout 只会读取第一个单词,而您应该使用 getline 读取整行” ?如果是,您应该在问题中提及这一点
  • cin &gt;&gt; sentence; 不起作用。具体来说,它会一直读取到第一个空格。该错误不在显示的代码中。您可能希望按照上面 cmets 中的建议使用 std::getline()
  • 为什么你的标题是“strlen 的递归版本”,而你的问题却与此完全无关?错误识别问题的问题是人们会搜索“strlen 的递归版本”,并遇到与读取输入有关的线程。

标签: c++ string recursion c-strings


【解决方案1】:

已经有标准 C 函数 strlen 具有以下声明

size_t strlen( const char *s );

所以你的递归函数应该有相同的声明。可以通过以下方式实现

size_t strlen( const char *s )
{
    return *s == '\0' ? 0 : 1 + strlen( s + 1 );
}

测试函数的程序可能看起来像

#include <iostream>
#include <string>
#include <limits>

size_t strlen( const char *s )
{
    return *s == '\0' ? 0 : 1 + strlen( s + 1 );
}

int main()
{
    char choice;

    do
    {
        std::cout << "Enter a sentence: ";

        std::string sentence;

        std::getline( std::cin, sentence );

        std::cout << "The length of the sentence is "
                  << strlen( sentence.c_str() )
                  << '\n';

        std::cout << "Do you want to have another run (Y/N)? ";

        std::cin >> choice;
        std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
    } while ( choice == 'y' || choice == 'Y' );        
}

它的输出可能是

Enter a sentence: Hello user12446497
The length of the sentence is 18
Do you want to have another run (Y/N)? n

【讨论】:

  • 虽然这可行,但我在我的代码中进行了尝试。我不确定我是否可以使用这种方法。它与“函数看起来像这样:int str_length(char s[])”的教师评论不同,我更喜欢你的方式,因为它不会限制字符串的长度。 .
  • @user12446497 如果需要,可以重新声明函数,如 int str_length( char s[] );虽然这个声明不好,因为它使读者感到困惑。例如,他们可以认为函数改变了;传递的字符串。
猜你喜欢
  • 1970-01-01
  • 2017-10-28
  • 1970-01-01
  • 2017-04-24
  • 1970-01-01
  • 2011-09-27
  • 1970-01-01
  • 2012-09-24
  • 2020-06-07
相关资源
最近更新 更多