你如何解决涉及递归的以下问题?
使用prototype实现一个函数, char *repeat(char *s, int n)
以便创建并返回一个由 n个重复的输入字符串组成的字符串.例如:如果输入为"Hello"且为3,则输出为"HelloHelloHello".仅使用递归构造.
我的解决方案在我看来非常难看,我正在寻找更清洁的东西.这是我的代码:
char *repeat(char *s, int n) {
if(n==0) {
char *ris = malloc(1);
ris[0] = '\0';
return ris;
}
int a = strlen(s);
char *ris = malloc(n*a+1);
char *ris_pre = repeat(s,n-1);
strcpy(ris,ris_pre);
strcpy(ris+(n-1)*a,s);
free(ris_pre);
return ris;
}
Run Code Online (Sandbox Code Playgroud)