programmmm
programmmm

Reputation: 19

C - repeat a string for a specific number of times in anothervariable

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?

Upvotes: 1

Views: 170

Answers (2)

tshiono
tshiono

Reputation: 22032

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

Upvotes: 1

Chris
Chris

Reputation: 36611

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

Upvotes: 1

Related Questions