我怎么写递归的Strrchr?

时间:2013-05-05 20:14:57

标签: c recursion

我想向Strrchr写入递归函数但我无法想到这个问题算法。我怎么写递归的Strrchr?

1 个答案:

答案 0 :(得分:0)

#include <stdio.h>

char *StrrchrR(const char *s, int c, char *find){
    if(s==NULL) return NULL;
    if(*s == '\0') return (c == '\0') ? (char*)s : find;
    return StrrchrR(s + 1, c, *s == c ? (char*)s : find);
}

char *Strrchr(const char *s, int c){
    return StrrchrR(s, c, NULL);
}
/*
char *Strrchr(const char *s, int c){
    char *ret;
    if(s == NULL)return NULL;
    if(*s=='\0') return (c == '\0') ? (char*)s : NULL;
    if(ret = Strrchr(s + 1, c)) return ret;
    if(*s == c) return (char*)s;
    return NULL;
}
*/    
int main(void){
    const char *str = "abcabdefg";
    char *cp;

    cp=Strrchr(str, '\0');
    printf("%c\n", *--cp);//g
    cp=Strrchr(str, 'b');
    printf("%c\n", *++cp);//d
    cp=Strrchr(str, 'z');
    if(!cp)printf("NULL\n");//NULL
    return 0;
}