Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading