小编ran*_*dom的帖子

在C中递归练习

你如何解决涉及递归的以下问题?

使用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)

c string recursion

6
推荐指数
2
解决办法
1539
查看次数

标签 统计

c ×1

recursion ×1

string ×1