2014-02-09 60 views
6

Kra!
我想“美化”我的飞镖脚本之一的输出,就像这样:不用循环多次打印相同的字符

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

<Paragraph> 

我不知道是否有特别简单和/或优化的方式打印相同的字符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次。

谢谢。

回答

6

我用这种方式。

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` 
----------------------------------------- 
+0

哇,绝对更具可读性和优雅!我不相信像你这样使用普通的'List'更好的方法。 – Diti