+ 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

28th Mar 2020, 4:37 PM
Ali Kh
Ali Kh - avatar
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.
28th Mar 2020, 5:23 PM
HonFu
HonFu - avatar
+ 6
fun srtlen(str, count) { if str is empty return count else return strlen(str.pop(),count+1) } pseudo code
28th Mar 2020, 5:38 PM
Oma Falk
Oma Falk - avatar
+ 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;
28th Mar 2020, 5:28 PM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 3
Copypaste it exactly as I wrote it in my comment. Don't change it. I did it myself - it does work.
28th Mar 2020, 5:38 PM
HonFu
HonFu - avatar
+ 3
It worked HonFu !! Your correction above .. I will try to under stand it though but really thank you for your help And what a clever Idea Oma Falk thanks for sharing
28th Mar 2020, 5:43 PM
Ali Kh
Ali Kh - avatar
+ 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?
28th Mar 2020, 5:32 PM
HonFu
HonFu - avatar
+ 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
28th Mar 2020, 5:37 PM
Ali Kh
Ali Kh - avatar
29th Mar 2020, 4:06 PM
narayanaprasad
narayanaprasad - avatar
+ 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
28th Mar 2020, 5:30 PM
Ali Kh
Ali Kh - avatar
0
HonFu will try it now .. meanwhile check this solution https://code.sololearn.com/WruTkIeycNTh/?ref=app
28th Mar 2020, 5:36 PM
Ali Kh
Ali Kh - avatar