Trying to determine string length 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 do not know how to navigate a line.

+6
source share
6 answers

Hint: use substr() in your recursion.

In addition, you have two basic options. One of them has three problems:

  • it has a syntax error;
  • it relies on being able to calculate the length of the string (which is what your function should do);
  • This is not necessary if you have a different base case.
+10
source

I do not think your example is meaningful, you use length , which already returns the length of your calculation. If I were your mentor, I would not accept this as an acceptable solution.

You probably need to use const char*

 int count(const char* s){ if(*s == '\0') return 0; return 1 + count(s + 1); } 
+3
source

If your goal is to cross a string, I suggest using an iterator (see std::string::begin ).

 template<typename It> int count(It const begin, It const end) { return (begin != end ? count(begin + 1, end) + 1 : 0); } int count(std::string const& s) { return count(s.begin(), s.end()); } 
+1
source

You might want to use substr .

+1
source

I know that you want C ++ - a solution, but still. Sometimes C is better than C ++.

  int count (const char * s)
 {
   if (* s == 0)
     return 0;
   else return 1 + count (++ s);
 };

Call as count (str.c_str ()).

0
source
  #include<stdio.h> main(){ char str1[100]; gets(str1); int i=0;i=len(str1,i);printf(" \nlength of string is %d",i); } int len(char s1[],int i) { printf("\n%c",s1[i]); int sum=0,count =1; if(s1[i] == '\0') return 0; else return (count += len(s1,++i)); } 
0
source

All Articles