【问题标题】:Printing the same character several times without a loop多次打印同一个字符而不循环
【发布时间】:2014-03-06 19:50:26
【问题描述】:

我想“美化”我的一个 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 次。

【问题讨论】:

    标签: dart pretty-print iterable


    【解决方案1】:

    最初的答案是 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 为零或负数,则返回一个空字符串。

    【讨论】:

      【解决方案2】:

      我用这种方式。

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

      【讨论】:

      • 哇,绝对更具可读性和优雅!我不相信一定有更优化的方式来使用普通的Lists,就像你做的那样。
      • 那是6年前的事了,6年前就给出了答案。你还想要什么评论?这些年是否需要回到过去,重新审视当时发生的一切,重新思考当时的一切,并得出一个结论,这是错误的答案?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多