Write a recursive int valued method len that accepts a stri
Write a recursive, int -valued method , 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 .
Solution
Here is the C++ implementation:
EXPLANATION:
The len function returns the number of characters in a string:
To get the last letter of a string, you might be tempted to try something like this:
//That won’t work. Because It causes the runtime error IndexError: string index out of range.
SOLUTION
int len(string s){
if (s.length()==0){
return 0;
}else{
return 1+(len(s.erase(0,1)));
}
}
| int len(string s){ if (s.length()==0){ return 0; }else{ return 1+(len(s.erase(0,1))); } } |
