简体   繁体   English

如何像在 python 中一样将 C 中的字符串相乘?

[英]how can I multiply strings in C like I do in python?

in python you can easily type:在 python 中,您可以轻松输入:

str = "hi"
print(str * 10)

and the output would be hi printed 10 times. output 将被打印 10 次。 I'm currently learning how to code in C and I have to do this.我目前正在学习如何在 C 中编码,我必须这样做。 Can someone teach me how I can do this kind of thing in C?有人可以教我如何在 C 中做这种事情吗? Thanks in advance提前致谢

Use for() loop:使用for()循环:

Example:例子:

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

And if you need to actually multiply the string (not just print n times) you can use the following mulstr() , just don't forget to test for NULL and to free() :如果您需要实际乘以字符串(不仅仅是打印 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);
  }
}

Using for-loop is the best way to implement this.使用for 循环是实现这一点的最佳方式。

You can just create a customized print function which will do the same thing as python does.您可以只创建一个自定义print function 它将与python执行相同的操作。 I am just giving a prototype here.我只是在这里给出一个原型。

#include <stdio.h>

void print(char *string,int n)
{
    int i;
    for(i=0;i<n;i++)
    {
     printf("%s\n",string);   
    }
}

int main()
{
    char *str="Hi";
    print(str,2);
    return 0;
}

Here second argument in the function n will tell you how many times you want to print the string . function n中的第二个参数将告诉您要打印string多少次。

The output will look like output 看起来像

Hi
Hi

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

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