【问题标题】:Specified letter count with recursion递归指定字母计数
【发布时间】:2014-12-09 20:32:09
【问题描述】:

我正在尝试编写一个递归算法来计算用户指定的字母。但是,我被困在两种情况下。首先,我想我必须得到2 结果,我不能。其次,如果没有限制键,例如用户指定为z的限制字符,如何将字符扫描到结束字符g?这个问题对我来说有点复杂。我需要你的建议和想法。谢谢大家的回答。

示例字符串为:how are you i am testing

另一个例子:

#include <stdio.h>

int lettercount(char* str, char key, char limit);

int main(){

    char test[]="how are you  i am testing";
    int num;

    num=lettercount(test,'a','t');

    printf("%d",num);

    return 0;
}
int lettercount(char* str, char key, char limit)
{
    int count = 0;

    if(str[0] == limit)
    {
        return 0;
    }
    else if(str[0] == key)
    {
        lettercount(&str[1], key, limit);
        count++;
    }
    else
        lettercount(&str[1], key, limit);

        return count;
}

【问题讨论】:

  • 除了检查它是否等于limit之外,您还需要检查str[0]是否为NUL终止符'\0'。此外,您从lettercount 函数返回一个count,但在递归调用该函数时忽略了返回值。
  • 嗯,是的,您对 NULL 的看法是正确的。我返回数? @user3386109
  • 你函数的最后一行是return count;

标签: c arrays recursion


【解决方案1】:
as the code is unwinding from the recursion(s)
it needs to accumulate the count
the following code should work for your needs.
Note: this returns 0 if key and limit are the same char

int lettercount(char* str, char key, char limit)
{
    int count = 0;

    if(str[0] == limit)
    {
        return 0;
    }

    // implied else, more char in string to check

    if(str[0] == key)
    {
        count++;
    }

    count += lettercount(&str[1], key, limit);

    return count;
} // end function: lettercount

【讨论】:

    【解决方案2】:

    使用递归函数,您需要 3 个东西。 (1) 设置函数中为下次调用做准备; (2) 递归调用;和(3) 一种终止递归的方法。这是一种方法。 注意:为了便于阅读,下面代码中的版本是long版本,末尾包含了short版本:

    #include <stdio.h>
    
    /* recursively find the number of occurrences
    of 'c' in 's' (n is provided as '0')
    */
    int countchar (char *s, char c, int n)
    {
        char *p = s;
        if (!*p)
            return n;
    
        if (*p == c)
            n = countchar (p+1, c, n+1);
        else
            n = countchar (p+1, c, n);
    
        return n;
    }
    
    int main (int argc, char **argv) {
    
        if (argc < 3) {
            fprintf (stderr, "\n error: insufficient input. Usage:  %s <string> <char>\n\n", argv[0]);
            return 1;
        }
    
        int count = countchar (argv[1], *argv[2], 0);
    
        printf ("\n There are '%d' '%c's in: %s\n\n", count, *argv[2], argv[1]);
    
        return 0;
    }
    

    输出:

    $ ./bin/rec_c_in_s "strings of s'es for summing"  s
    
     There are '5' 's's in: strings of s'es for summing
    

    您可以使函数更短,但可读性稍差:

    int countchar (char *s, char c, int n)
    {
        char *p = s;
        if (!*p) return n;
    
        return countchar (p+1, c, (*p == c) ? n+1 : n);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-20
      • 2017-04-14
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-28
      • 2012-10-22
      相关资源
      最近更新 更多