代码之家  ›  专栏  ›  技术社区  ›  Augie Li

Dart:如何从字符串中获取char,并进行比较

  •  1
  • Augie Li  · 技术社区  · 7 年前

    我试图从字符串中获取char,并进行比较:

    String aStr = ReadString(inputs);
    String bStr = ReadString(inputs);
    
    int diff = 0;
    for (int i = 0; i < n; i++) {
      if (aStr.codeUnitAt(i) != bStr.codeUnitAt(i)) {
        diff++;
      }
    }
    

    但是,在编译过程中出现了以下错误:

    Unhandled exception:
    RangeError (index): Invalid value: Not in range 0..6, inclusive: 7
    #0      String.codeUnitAt (dart:core-patch/string_patch.dart:927)
    #1      BoomerangDecoration (file:<>/HCPast/bin/hcpast.dart:49:16)
    <asynchronous suspension>
    #2      main (file:<>/HCPast/bin/hcpast.dart:9:9)
    <asynchronous suspension>
    #3      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:263)
    #4      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:151)
    

    我也试过charCodeAt,但据说它不是String的方法。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Augie Li    7 年前

    我再查一遍,已经过了补考期了。原因应该是索引超出了字符串的结尾。