advena
advena

Reputation: 83

How to print a string consisting of a char repeated a variable number of times in C?

In Python, one can print XXXX using print "X"*4; Is there any easy equivalent in C?

Upvotes: 0

Views: 1884

Answers (4)

SwiftMango
SwiftMango

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

ikegami
ikegami

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

fvdalcin
fvdalcin

Reputation: 1047

Yes. Welcome to C:

int i;
for (i=0; i<4; i++)
    printf("X");

Upvotes: 1

Dima
Dima

Reputation: 39419

Not really. In C you would need to use a loop.

Upvotes: 0

Related Questions