[英]What would be the simplest way to alpha sort an array of chars in C?
[英]What would be the fastest way to create a string of n chars in C
创建重复字符字符串的最快/最短方法是什么。
例如, n = 10, char = '*', resulting allocated string: **********
使用memset 。
int n = 10;
char c = '*';
char* buf = malloc(n+1);
memset(buf, c, n);
buf[n] = '\0';
free(buf);
memset(buf, '*', 10); buf[10]=0;
将'*'
和10
替换为所需的值,如果长度未知或可能很大,请使用buf=malloc(n+1);
获得缓冲。
char *allocate(int c, size_t n)
{
if(!c) return calloc(n + 1);
char *s = malloc(n + 1);
memset(s, c, n);
s[n] = '\0';
return s;
}
老实说,您为什么要尝试最快呢? 为什么不这样做,然后在需要时加快速度呢?
特别是,如果您仅创建它来输出它,则可以
void printtimes(int c, size_t n, FILE *f)
{
while(n--) fputc(c, f);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.