29

I would like to "beautify" the output of one of my Dart scripts, like so:

-----------------------------------------
OpenPGP signing notes from key `CD42FF00`
-----------------------------------------

<Paragraph>

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

Learning from this answer, for the purpose of this question, I wrote the following minimal code, which makes use of the core Iterable 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 output, 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 times.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Diti
  • 1,454
  • 3
  • 23
  • 38

2 Answers2

45

The original answer is from 2014, so there must have been some updates to the Dart language: a simple string multiplied by an int works.

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

And this will be printed as:

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

See Dart String's multiply * operator docs:

Creates a new string by concatenating this string with itself a number of times.

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

Returns an empty string if times is zero or negative.

Vince Varga
  • 6,101
  • 6
  • 43
  • 60
12

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`
-----------------------------------------
mezoni
  • 10,684
  • 4
  • 32
  • 54
  • Woah, definitely more readable and elegant! I don't believe there must be a more optimized way of using plain `List`s like you did. – Diti Feb 09 '14 at 16:12
  • That was 6 years ago and the answer was given 6 years ago. What else do you want as a comment? It is need to return to the past for these years, take a new look at everything that was happening at that time, rethink everything that was then and give out a verdict that this is the wrong answer? – mezoni Apr 08 '20 at 12:13