5

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?

4
  • Nothing that will be more effective than a loop. Oct 11 '16 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?
    – Mirror318
    Oct 11 '16 at 1:11
  • That would depend on whether or not count has a reasonable limit. Oct 11 '16 at 1:20
  • For(let str = ‘a’; str.length<6; str+=‘a’){ Console.log(str) }
    – Jackie
    Feb 27 '20 at 3:21
1

A more simple "noob" way could also be:

int count = 6

for(int i=0; i<count; i++)
{
  Serial.print("b");
}

Serial.println();
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
    – Mirror318
    Oct 12 '16 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.

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.

1
  • 1
    Nice! You can also overload "*" so that OP's exact syntax would work!
    – xyz
    Oct 11 '16 at 14:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.