2014-12-09 2 views
0

사용자가 지정한 문자 수를 계산하는 재귀 알고리즘을 작성하려고합니다. 하지만, 나는 두 가지 경우에 갇혀있다. 첫째, 결과로 2을 얻어야한다고 생각합니다. 둘째, 제한 키가 없으면 (예 : 사용자가 z으로 지정한 제한 문자) 여기에서 문자를 마지막 문자까지 스캔 할 수있는 방법 g? 문제는 나를 위해 약간 복잡합니다. 당신의 충고와 아이디어가 필요합니다. 모든 감사의 답변을 주셔서 감사합니다.재귀가 지정된 문자 수

예를 들어 문자열은 다음과 같습니다 how are you i am testing

또 다른 예 : 재귀 함수와

example

#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; 
} 
+0

str [0]이 'limit'과 같은지 확인하는 것 외에도 NUL 터미네이터 ''\ 0 ''인지 확인해야합니다. 또한'lettercount' 함수에서'count'를 리턴하지만, 재귀 적으로 함수를 호출 할 때 리턴 값을 무시합니다. – user3386109

+0

음, 네가 NULL에 대해 옳다. 나는 카운트를 반환? @ user3386109 –

+0

함수의 마지막 줄은'return count;'입니다. – user3386109

답변

0
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 
0

, 당신은 3 일을해야합니다. (1)다음 호출을 준비하는 함수에을 설정하십시오. (2)재귀 호출; 및 (3)재귀를 종료하는 방법. 여기 하나의 접근 방식이 있습니다. 참고 :

#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); 
}