【问题标题】:Weird behavior of string methods in dartdart 中字符串方法的奇怪行为
【发布时间】:2021-03-16 13:57:50
【问题描述】:

我正在尝试检查字符串变量中字符“-”的索引。尽管变量包含“-”,dart indexof 和 lastIndexof 返回 -1。我还检查了“包含”方法,它同样返回该字符串不包含“-”,尽管它确实包含。代码如下:

     String s = "Oh yes, the past can hurt. But the way I see it, you can either run from it or learn from it. – The Lion King";
         int x = s.indexOf('-');
        print(x);
         if(s.contains("-")){
          // print("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv............");
           print("Yipee string contains -");
         }else{
           print("string does not contain -");
              // the following is the output:
             //string does not contain -
         }
     
         if(x == -1){
         print(x);
         // It prints out -1 
        }else{
           
          print(x);
           return s.substring(0,x);
         }

看在上帝的份上,我做错了什么?

【问题讨论】:

  • 你能不能把字符复制到– The Lion King,然后粘贴到你的indexOf(...)contains(...)。我认为这个角色是不同的。

标签: flutter dart


【解决方案1】:

'–''-' 是两个不同的字符。看看第一个如何稍微长一些。

void main() {
  final str = '–-';
  print(str.codeUnitAt(0)); // 8211 (En Dash)
  print(str.codeUnitAt(1)); // 45 (Hyphen)
}

如果你想找到其中一个,也可以使用Regular Expressions

在以下代码示例中,str1str2 几乎相同。我只是颠倒了'–''-'的位置。

void main() {
  final str1 = '123456–78-90';
  final str2 = '123456-78–90';
  final regExp = RegExp(r'[–-]');
  print(regExp.firstMatch(str1)?.start); // 6
  print(regExp.firstMatch(str2)?.start); // 6
}

【讨论】:

  • 谢谢伙计。这行得通。这两个标志看起来很像我的眼睛。再次感谢您的帮助。
【解决方案2】:

您正在搜索的字符 - 与文本中的字符 不同。注意两者的长度差异。

【讨论】:

    【解决方案3】:

    字符串中的字符是 短划线,比连字符 (-) 稍宽,但比短划线 (-) 窄。 因此,contains 函数无法检测连字符,因为存在破折号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 2023-03-20
      • 2015-03-12
      • 1970-01-01
      • 2020-06-18
      • 2015-05-29
      相关资源
      最近更新 更多