Printing the same character multiple times without a loop

Kra!
I would like to “decorate” the output of one of my Dart scripts, for example:

----------------------------------------- OpenPGP signing notes from key `CD42FF00` ----------------------------------------- <Paragraph> 

And I wonder if there is a particularly simple and / or optimized way to print the same character x times in Dart . In Python, print "-" * x will print the character - x .

Studying this answer , for this question I wrote the following minimal code that uses the Iterable main class:

 main() { // Obtained with '-'.codeUnitAt(0) const int FILLER_CHAR = 45; String headerTxt; Iterable headerBox; headerTxt = 'OpenPGP signing notes from key `CD42FF00`'; headerBox = new Iterable.generate(headerTxt.length, (e) => FILLER_CHAR); print(new String.fromCharCodes(headerBox)); print(headerTxt); print(new String.fromCharCodes(headerBox)); // ... } 

This gives the expected result, but is there a better way in Dart to print a character (or string) x times? In my example, I want to print the character - headerTxt.length .

Thanks.

+8
source share
2 answers

I use this way.

 void main() { print(new List.filled(40, "-").join()); } 

So, your case.

 main() { const String FILLER = "-"; String headerTxt; String headerBox; headerTxt = 'OpenPGP signing notes from key `CD42FF00`'; headerBox = new List.filled(headerTxt.length, FILLER).join(); print(headerBox); print(headerTxt); print(headerBox); // ... } 

Output:

 ----------------------------------------- OpenPGP signing notes from key `CD42FF00` ----------------------------------------- 
+9
source

The original answer was from 2014, so there must have been some darts language updates: a simple string multiplied by a number works .

 main() { String title = 'Dart: Strings can be "multiplied"'; String line = '-' * title.length print(line); print(title); print(line); } 

And it will be printed as:

 --------------------------------- Dart: Strings can be "multiplied" --------------------------------- 

See Dart String multiply * operator docs :

Creates a new line, concatenating this line with itself several times.

The result of str * n equivalent to str + str + ... (n times) ... + str '.

Returns an empty string if times is zero or negative.

0
source

All Articles