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

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

<Paragraph>

我想知道printing the same character 100 times in Dart是否有一种特别简单和/或优化的方式.在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));
  // ...
}

这给出了预期的输出,但是is there a better way英寸的省道可以打印一个字符(或字符串)x次吗?在我的示例中,我想将"-"个字符打印headerTxt.length次.

推荐答案

最初的答案是2014年的,所以Dart语言肯定有一些更新:a simple string multiplied by an 100 works.

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为零或负,则返回空字符串.

Dart相关问答推荐

S,返回Future.sync()的函数和不需要等待的异步函数有什么区别?

在 Dart 中使用隔离优于异步的优势

在 Flutter 中从树中临 timeshift 除时保留小部件状态

ListView 不会刷新,而附加列表会刷新 (Flutter)

在 Column Flutter 中居中展开 ListView

可调用云函数错误:响应缺少数据字段

如何为 spawnUri 动态构建 Dart 脚本?

在 Flutter 中保持响应的同时制作持久的背景图像

Google Dart支持mixins吗?

如何在flatter中使用SQFlite更新数据库表

如何在dart中获取 map 的键列表?

错误:无法将参数类型void Function(ImageInfo, bool)分配给参数类型ImageStreamListener

如何提取dart/Flutter视频元数据

如何仅从 DateTime.now() 中提取时间;

将符号转换为字符串

polymer SEO 是否友好?

如何在 Dart SDK 0.4+ 中使用 setInterval/setTimeout

Dart 中的错误与异常

如何在 Dart 中运行重复出现的函数?

字符串枚举