在没有循环的情况下多次打印相同的字符

Dit*_*iti 9 iterable pretty-print dart

克拉!
我想"美化"我的一个Dart脚本的输出,如下所示:

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

<Paragraph>
Run Code Online (Sandbox Code Playgroud)

我想知道在Dart中是否有一种特别简单和/或优化的方式来打印相同的角色x时间.在Python中,print "-" * x会打印-字符x时间.

这个答案中学习,为了这个问题的目的,我编写了以下最小代码,它使用了核心Iterable类:

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));
  // ...
}
Run Code Online (Sandbox Code Playgroud)

这给出了预期的输出,但在Dart中有更好的方法来打印字符(或字符串)x次数吗?在我的例子中,我想打印-字符headerTxt.length时间.

谢谢.

Vin*_*rga 23

最初的答案是从 2014 年开始的,所以 Dart 语言肯定有一些更新:一个简单的字符串乘以一个int作品

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

这将打印为:

---------------------------------
Dart: Strings can be "multiplied"
---------------------------------
Run Code Online (Sandbox Code Playgroud)

请参阅 DartString的乘法*运算符文档

通过将此字符串与其自身连接多次来创建一个新字符串。

的结果str * n等价于str + str + ...(n times)... + str

如果times为零或负数,则返回空字符串。


mez*_*oni 9

我用这种方式.

void main() {
  print(new List.filled(40, "-").join());
}
Run Code Online (Sandbox Code Playgroud)

所以,你的情况.

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);
  // ...
}
Run Code Online (Sandbox Code Playgroud)

输出:

-----------------------------------------
OpenPGP signing notes from key `CD42FF00`
-----------------------------------------
Run Code Online (Sandbox Code Playgroud)