如何使用C递归地计算字符串中非空白字符的数量?

如何使用C递归地计算字符串中非空白字符的数量?,c,C,这个程序的主要问题是,它不会计算字符串中的空格数,即使遇到空格时它应该减少计数(开始时计数设置为字符串的长度)。我是否没有正确地检查空白(通过检查“”),或者我的递归案例是否有问题 # include <stdio.h> # include <string.h> // function to reverse string and count its length int rPrint(char *str, int count) { if(*str) {

这个程序的主要问题是,它不会计算字符串中的空格数,即使遇到空格时它应该减少计数(开始时计数设置为字符串的长度)。我是否没有正确地检查空白(通过检查“”),或者我的递归案例是否有问题

# 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);
}
#包括
#包括
//函数反转字符串并计算其长度
整数rPrint(字符*str,整数计数)
{
如果(*str)
{
如果(*str!='')
rPrint(str+1,计数);
其他的
rPrint(str+1,count-1);
printf(“%c”,*str);
}
返回计数;
}
int main()
{
字符字符串[28]=“”;
整数计数=0;
printf(“请输入字符串:”);
获取(字符串);
count=rPrint(字符串,strlen(字符串));
printf(“\n字符串中的非空字符数为%d.”,count);
}

您没有使用递归调用的返回值

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

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

您没有使用递归调用的返回值

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

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

当你递归时,你丢弃了结果。试一试

count = rPrint(str+1, count);
等等


更一般地说,作为一种调试方法,您应该学会将
printf()
语句放入函数中,以打印出它们正在执行的操作….

当您递归时,您会丢弃结果。试一试

count = rPrint(str+1, count);
等等


更一般地说,作为一种调试方法,您应该学会将
printf()
语句放入函数中,以打印出它们正在执行的操作….

当您返回
count
时,您不会使用递归调用返回的值。次要问题:从技术上讲,“空白”除了空格外,还包括制表符,换行符等。当您返回<代码>计数时,您不使用递归调用返回的值。次要问题:从技术上讲,“空白”除了空格外,还包括制表符、换行符等。