我想向 Strrcr 编写递归函数,但我想不出这个问题算法。如何编写递归 Strrchr?
问问题
611 次
1 回答
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;
}
于 2013-05-05T22:07:21.697 回答