2014-02-09 64 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