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

问题描述 投票:8回答:2

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

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

<Paragraph>

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

this answer学习,为了这个问题的目的,我编写了以下最小代码,它使用了核心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));
  // ...
}

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

谢谢。

dart pretty-print iterable
2个回答
1
投票

原始答案是从2014年开始的,因此必须对Dart语言进行一些更新:一个简单的字符串乘以int作品。

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

这将打印为:

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

见Dart String's multiply * operator docs

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

str * n的结果相当于str + str + ...(n times)... + str

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


9
投票

我用这种方式。

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

所以,你的情况。

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);
  // ...
}

输出:

-----------------------------------------
OpenPGP signing notes from key `CD42FF00`
-----------------------------------------
© www.soinside.com 2019 - 2024. All rights reserved.