What would be the fastest/shortest way 开发者_运维问答to create a string of repeating characters.
For instance, n = 10, char = '*', resulting allocated string: **********
Use 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;
Replace '*'
and 10
with the values you want, and if the length is not known in advance and could be large, use buf=malloc(n+1);
to get your buffer.
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;
}
Honestly, why are you trying to do it fastest? Why not just do it, and then speed it up later if you need to?
Particularly, if you're only creating this to output it, you could just
void printtimes(int c, size_t n, FILE *f)
{
while(n--) fputc(c, f);
}
精彩评论