I am doing online work using CodeLab for C++ and am not sure what’s wrong with my code. Here is the question:
Write a recursive, int-valued function, len, that accepts a string and returns the number of characters in the string.
The length of a string is:
0 if the string is the empty string (“”).
1 more than the length of the rest of the string beyond the first character.
And here’s my code:
int len(string s)
{
if (s.length()==0)
return 0;
else
{
return 1+(len(s)-1);
}
}
It says I have a run-time error.
Any help?
Thanks.
Well here:
The length of the string never decreases. So you will eventually have a stackoverflow because you never hit your base case
(s.length() == 0).You need to get a substring where the length of s decreases by 1:Hopefully this is purely academic, because
std::stringhas alengthmethod that will run in constant time. (Not to mention erasing from the front of a string is probably horribly inefficient– see the other answers that work withchar *)