gpt4 book ai didi

dart - 多次打印相同的字符而不循环

转载 作者:行者123 更新时间:2023-12-04 03:37:48 25 4
gpt4 key购买 nike

克拉!
我想“美化”我的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:

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.

关于dart - 多次打印相同的字符而不循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21660984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com