Reputation: 1489
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.
Upvotes: 6
Views: 8182
Reputation: 2960
If you don't need the value of i
afterwards, either:
for(;i--;printf("x"));
or
while(i--)printf("x");
do it in 22 chars. If you do need i
afterwards, and you've got a spare variable j
lying around, the shortest using-a-loop I've found uses 25 characters:
for(j=i;j--;printf("x"));
Using a function the best I can do is 28 chars for the function + 5 per call:
r(x){x&&printf("x")&r(--x);}
int main()
{
int i=12;
r(i);
}
Upvotes: 1
Reputation: 13436
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).
Upvotes: 2
Reputation: 6568
Super dirty trick if you're interested in one specific char
#include <stdio.h>
const char *very_long_single_char_string = "___________________________________";
int main()
{
int i = 4;
printf("%.*s",i, very_long_single_char_string);
}
Result:
____
Upvotes: 0