gpt4 book ai didi

c - 如何编写递归 Strrchr?

转载 作者:行者123 更新时间:2023-11-30 21:45:08 26 4
gpt4 key购买 nike

我想为 Strrchr 编写递归函数,但我无法思考这个问题的算法。如何编写递归 Strrchr?

最佳答案

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

关于c - 如何编写递归 Strrchr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16388687/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com