克拉! 我想“美化”我的一个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
次。
谢谢。
原始答案是从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
为零或负数,则返回空字符串。
我用这种方式。
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`
-----------------------------------------