Reputation: 83
In Python, one can print XXXX
using print "X"*4;
Is there any easy equivalent in C?
Upvotes: 0
Views: 1884
Reputation: 15294
No there is no standard library in C that can do that, but you can always implement easily with yourself. A simple implementation in C:
char * strmul(const char * src, size_t times) {
size_t s_len = strlen(src);
char * res = (char*)malloc(s_len * times + 1);
int i;
for(i = 0; i < times; i++) {
strcpy(res + s_len * i, src);
}
return res;
}
Improved version as suggested by @ikegami
char * strmul(const char * src, size_t times) {
size_t s_len = strlen(src);
char * res = (char*)malloc(s_len * times + 1);
int i;
for(i = 0; i < times; i++) {
memcpy(res + s_len * i, src);
}
res[s_len * times + 1] = '\0';
return res;
}
Upvotes: 0
Reputation: 386331
C doesn't have much in the way of builtin/standard library, so you'd have to go through the process of allocating a new buffer and concatenating four strings to it, then freeing the buffer, it's simpler just to print "X" four times.
int i;
for (i=0; i<4; ++i) {
printf("X");
}
printf("\n");
You could write your own, though.
char* x(const char* s, unsigned int reps) {
size_t len = strlen(s);
char* buf = (char*)malloc(len*reps + 1);
while (reps--) {
memcpy(buf, s, len);
buf += len;
}
*buf = '\0';
return buf;
}
char* repeated = x("X", 4);
printf("%s\n", repeated);
free(repeated);
But as you can see, the result is almost as long.
Upvotes: 2