开发者

What would be the fastest way to create a string of n chars in C

开发者 https://www.devze.com 2023-01-26 14:49 出处:网络
What would be the fastest/shortest way 开发者_运维问答to create a string of repeating characters.

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

精彩评论

暂无评论...
验证码 换一张
取 消