简体   繁体   中英

How can I recursively count the number of non-whitespace characters in a string using C?

The main problem with this program is that it won't count the number of whitespaces in a string, even though it's supposed to decrement the count if it encounters a whitespace (it starts out with count set to the string's length). Am I not checking for whitespaces correctly (by checking for ' '), or is there something wrong with my recursion cases?

# include <stdio.h>
# include <string.h>

// function to reverse string and count its length
int rPrint(char *str, int count)
{
   if(*str)
   {
       if(*str != ' ')   
           rPrint(str+1, count);
       else
           rPrint(str+1, count - 1);

       printf("%c", *str);
   }
   return count;
}

int main()
{
   char string[28] = "";
   int count = 0;

   printf("Please enter a string: ");
   gets(string);

   count = rPrint(string, strlen(string));

   printf("\nThe number of non-blank characters in the string is %d.", count);
}

You are not using the return value of your recursive calls.

   if(*str != ' ')
       rPrint(str+1, count);
   else
       rPrint(str+1, count - 1);

should be

   if(*str != ' ')
       count = rPrint(str+1, count);
   else
       count = rPrint(str+1, count - 1);

When you recurse, you throw away the result. Try

count = rPrint(str+1, count);

etc.

More generally, as a debugging method you should learn to put printf() statements into your functions to print out what they're doing....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM