6

I want to have a line like this

Serial.println(count*"B");

So if count=6, it would print BBBBBB, etc.

Is there anything like this for arduino?

asked Oct 11, 2016 at 0:33
4
  • Nothing that will be more effective than a loop. Commented Oct 11, 2016 at 0:35
  • A loop that prints char by char, or a loop that builds a string, and is printed at the end of the loop? Commented Oct 11, 2016 at 1:11
  • That would depend on whether or not count has a reasonable limit. Commented Oct 11, 2016 at 1:20
  • For(let str = ‘a’; str.length<6; str+=‘a’){ Console.log(str) } Commented Feb 27, 2020 at 3:21

3 Answers 3

1

A more simple "noob" way could also be:

int count = 6
for(int i=0; i<count; i++)
{
 Serial.print("b");
}
Serial.println();
answered Oct 11, 2016 at 11:38
1
  • This is what I ended up doing (although made the for loop one line). I wasn't really looking to make my own method like the others have done, I was just hoping there'd be some kind of string * int syntax Commented Oct 12, 2016 at 1:08
3

You can write a helper function to do it, like this:

void printRepeat (Stream & device, const char * str, unsigned int count)
 {
 while (count-- > 0)
 device.print (str);
 } // end of printRepeat
void setup() 
 {
 Serial.begin (115200);
 printRepeat (Serial, "-", 20);
 Serial.println ();
 } // end of setup
void loop() 
{
 printRepeat (Serial, "Hello, World! ", 5);
 Serial.println ();
 delay (500);
} // end of loop

The function printRepeat is passed a Stream argument, which can be something like Serial, Serial1, a SoftwareSerial instance, and so on.

answered Oct 11, 2016 at 3:02
2

Just for fun, here is a version of Nick Gammon's answer reformulated with some C++ magic:

// A "repeated string" that has no use except for being printable.
class RepeatedString : public Printable
{
public:
 RepeatedString(const char * str, unsigned int count)
 : _str(str), _count(count) {}
 size_t printTo(Print& p) const
 {
 size_t sz = 0;
 for (unsigned int i = 0; i < _count; i++)
 sz += p.print(_str);
 return sz;
 }
private:
 const char * _str;
 unsigned int _count;
};
void setup() 
{
 Serial.begin(115200);
 Serial.println(RepeatedString("-", 20));
}
void loop() 
{
 Serial.println(RepeatedString("Hello, World! ", 5));
 delay(500);
}

You can .print() and .println() the RepeatedStrings on anything that can print.

answered Oct 11, 2016 at 8:35
1
  • 1
    Nice! You can also overload "*" so that OP's exact syntax would work! Commented Oct 11, 2016 at 14:26

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.