Currently, I am attempting to repeat a single character in the least characters possible. as an example, I am actually using something similar to this to repeat a series of spaces:
printf("%*s",i,"");
And I was wondering if there was a similar, or even shorter/different way in C to repeat a string and print it out, as with the spaces.
I would like something similar to this if possible:
printf("%*s",i,"_");
However, as far as I know, that's not possible, however ideal it would be for me.
To clarify, in these examples the argument i represents the number of times I would like the character to repeat, i.e, the second example should output (if i was say, 12):
____________
NB: It does not necessarily have to be anything related to printf, however, it does have to be short.
Essentially, I would like to repeat one character a specified number of times and then output it.
Edit: I am currently using a for loops which allows me 31 characters, however by using a method similar to the above, I can cut down another 7 characters on top of that, due to the way the program is structured. So a loop is not really ideal.
You can use memset
:
void * memset ( void * ptr, int value, size_t num );
// Fill block of memory
// Sets the first num bytes of the block of memory pointed by ptr to the specified value
// (interpreted as an unsigned char).
So you would do, assuming dest
is your destination string :
memset(dest, '_', 12);
EDIT : This is a very "raw" solution. It does not put a '\0' at the end of the string, so you have to deal with that too if you want your string only to contain the repeated character and to be formatted the standard way. You of course have to deal with the fact that 12 might be bigger than the space allocated to dest
, too.
One last thing : the use of memset
is probably more efficient than anything you can do with using your own loops as memset
could be implemented in a very efficient way by your compiler (i.e., highly-optimized assembly code).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With