简体   繁体   English

C - 在另一个变量中重复一个字符串特定次数

[英]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...我想重复一个字符串 - 例如你好 - 对于特定数量的 imes - 例如 3 次 - 但它不起作用:) 该示例应如下所示:hellohellohello,但我没有得到 output 或者我得到 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?如果我删除 'ausgabe' 括号中的 'z',我得到 output HHHHHHHH%,而 z 我只是没有 output。bdy 可以帮我改变这个行为 - 更重要的是,了解它为什么这样做?

The strcat function is your friend. strcat function 是你的朋友。 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.我们可以为n源字符串调用一个足够长的缓冲区,再加上一个用于calloc终止符的缓冲区,然后将源字符串连接到该缓冲区n次。

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

As you are always referring *src , which is fixed to the first letter of src , the result looks like repeating it.由于您总是引用*src ,它固定为src的第一个字母,结果看起来像是在重复它。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM