+ 1
Counting string length using recursion
I was trying to make a function that counts the length of a string using recursion .. but I'm stuck I don't know what is wrong with my code especially line number 5.. I know we can use the length property but this isn't the case here https://code.sololearn.com/WFZ89n7sC6Z0/?ref=app https://code.sololearn.com/WFZ89n7sC6Z0/?ref=app
10 Respostas
+ 5
I've repaired your version minimally-invasively:
function length(str) {
if (str.length == 1) {return 1;}
var strArray = str.split("");
strArray.pop();
var strAgain = strArray.join("");
return strArray.length - (strArray.length-1) +
length(strAgain);
}
document.write(length("hey there"))
1.) You don't need a variable minus, just pop.
2.) You need to join the array.
3.) No enter after return.
Comment:
Was this a homework?
It seems somewhat strange to recurse like this through the string when you use method length anyway - you could have used it to begin with.
+ 6
fun srtlen(str, count) {
if str is empty return count
else return strlen(str.pop(),count+1)
}
pseudo code
+ 4
I don't understand what you're trying to do. string.length already returns the length of the string. And the other way would be to iterate over string using a loop and count up a variable until you reach the end. Recursively however doesn't make sense - at least not from a practical or performance oriented standpoint. But then I'd do it like this: pop the last character from the string and simply return
recusive_length(str) + 1;
and if the string is empty return 0;
+ 3
Copypaste it exactly as I wrote it in my comment. Don't change it.
I did it myself - it does work.
+ 2
Ali Kh, you shortened your array anyway by using pop - storing the value in a variable doesn't change anything about it.
Have you tried running my version?
+ 2
It didn't work tho 😅 .. wait I think I've spot the mistake .. when I declared the variable minus
var minus = strArray.pop();
that actually stores the "POPPED" out value not the string minus the last value
+ 2
https://www.geeksforgeeks.org/program-for-length-of-a-string-using-recursion/ may give the answer
+ 1
Thanks for your help HonFu but I don't think this will work ..
When you pop the array you will lessen the original string length before even counting it
0
HonFu will try it now .. meanwhile check this solution
https://code.sololearn.com/WruTkIeycNTh/?ref=app