It's a bit tricky to explain the question, but suppose two alternating chars must be shown:
for(int n=0; n<20; n++)
{
cout<<(n%2==0 ? 'X' : 'Y');
}
Is there a one-liner or more efficient way to accomplish the task above? (i.e. using something like <iomanip>
's setfill()
)?
Use string slicing to print the alternate characters in a string, e.g. print(string[::2]) . The slice will contain every other character of the original string. Copied! We used string slicing to print the alternate characters in a string.
Approach: In order for the string to be made up of only two alternating characters, it must satisfy the following conditions: All the characters at odd indices must be same. All the characters at even indices must be same.
I think I'd keep it simple:
static const char s[] ="XY";
for (int n=0; n<20; n++)
std::cout << s[n&1];
The other obvious possibility would be to just write out two characters at a time:
for (int n=0; n<total_length/2; n++)
std::cout << "XY";
If I work with strings and concise code matters a bit more than performance (like you have in Python), then I might write just this:
static const std::string pattern = "XY";
std::cout << pattern * n; //repeat pattern n times!
And to support this, I would add this functionality in my string library:
std::string operator * (std::string const & s, size_t n)
{
std::string result;
while(n--) result += s;
return result;
}
One you have this functionality, you can use it elsewhere also:
std::cout << std::string("foo") * 100; //repeat "foo" 100 times!
And if you have user-defined string literal, say _s
, then just write this:
std::cout << "foo"_s * 15; //too concise!!
std::cout << "XY"_s * n; //you can use this in your case!
Online demo.
Cool, isn't it?
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