Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to determine length of a string using recursion in C++

int count(string s){
    if(s == "")
      return 0;
    if(s.length == 1)
      return 1;
    return 1 + count() //This is what I can't figure out. How to traverse the string.
    //I just need a hint, not a full on answer.
}

I dont know how to traverse a string.

like image 456
corn_flakes Avatar asked Dec 11 '12 08:12

corn_flakes


1 Answers

Hint: use substr() in your recursion.

Also, you have two base cases. One of them has three issues:

  1. it has a syntax error in it;
  2. it relies on being able to compute the length of the string (which is what your function is supposed to do);
  3. it is unnecessary given that you have the other base case.
like image 115
NPE Avatar answered Sep 30 '22 20:09

NPE