1

I want to repeat a string - for example hello - for a specific number of imes - for example 3 times -, but it doesnt work :) The example should look like this: hellohellohello, but I get no output or i get HHHHHHHHHHH...

here is my code:

char *repeat_str(size_t count, char *src) {
  int length = strlen(src);
  int z = length;
  char *ausgabe = calloc((length*(count+1)), sizeof(char));
  for(int i = 0; i<=((int) count);i++){
    for(int j =0; j< length; j++){
      ausgabe[i+j+z] = src[j];
  }
  z=z*2;
  }
  //printf("%s\n", ausgabe);
  return(ausgabe);
}

If i remove the 'z' in the brackets of 'ausgabe', i get the output HHHHHHHH%, with the z I just get no output. Could bdy pls help me change this behavoiur - and more important, understant why it does that?

programmmm
  • 19
  • 6

2 Answers2

1

The strcat function is your friend. We can calloc a buffer long enough for n source strings, plus one for the null terminator, and then just concatenate the source string onto that buffer n times.

char *repeat_string(int n, const char *s) {
    int len = strlen(s) * n + 1;
    char *result = calloc(len, 1);

    if (!result) return NULL;

    for (int i = 0; i < n; i++) {
        strcat(result, s);
    }

    return result;
}
Chris
  • 26,361
  • 5
  • 21
  • 42
  • Thats a nice thing to know - thank you! – programmmm Dec 06 '22 at 07:25
  • Beware of the [Shlemiel the painter’s algorithm](https://www.joelonsoftware.com/2001/12/11/back-to-basics/). For very small `n`, that may be fine, but it may get very inefficient when `n` gets bigger sooner than you think. – Zakk Dec 06 '22 at 08:18
1

As you are always referring *src, which is fixed to the first letter of src, the result looks like repeating it. Would you please try instead:

char *repeat_str(size_t count, char *src) {
    int length = strlen(src);
    char *ausgabe = calloc(length * count + 1, sizeof(char));
    for (int i = 0; i < count; i++) {
        for (int j = 0; j < length; j++) {
            ausgabe[i * length + j] = src[j];
        }
    }
    //printf("%s\n", ausgabe);
    return ausgabe;
}
tshiono
  • 21,248
  • 2
  • 14
  • 22