如何像在 python 中那样在 C 中乘以字符串?

Ohh*_*hhh 2 c string

在 python 中,您可以轻松输入:

str = "hi"
print(str * 10)
Run Code Online (Sandbox Code Playgroud)

并且输出将被打印 10 次。我目前正在学习如何用 C 编写代码,我必须这样做。有人可以教我如何在 C 中做这种事情吗?提前致谢

nir*_*iry 7

使用for()循环:

例子:

#include <stdio.h>
int main() {
  char* str = "hi";
  for (int i = 0; i < 10; ++i) {
    printf("%s", str);
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您需要实际乘以字符串(不仅仅是打印 n 次),您可以使用以下内容mulstr(),只是不要忘记测试 NULL 和free()

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>

char* mulstr(char* str, size_t i) {
  size_t len = strlen(str);
  char* newstr = malloc(len * i + 1);
  if (newstr) {
    char* writer = newstr;
    for (; i; --i) {
      memcpy(writer, str, len);
      writer += len;
    }
    *writer = 0;
  } else {
    perror("malloc");
  }
  return newstr;
}

int main() {
  char* str = "hi";
  char* newstr = mulstr(str, 10);
  if (newstr) {
    printf("%s", newstr);
    free(newstr);
  }
}
Run Code Online (Sandbox Code Playgroud)