简体   繁体   中英

Weird behavior of string methods in dart

I am trying to check for the index of a character "-" in a string variable. Despite the fact that the variable contains "-", dart indexof and lastIndexof are returning -1. I also checked with "contain" method it is equally returning that string does not contain "-" despite the fact it does. Here is the code:

     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);
         }

Please for the love of God, what am i doing wrong?

'–' and '-' are two different characters. See how the first one is slightly longer.

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

If you want to find either one or the other, you can also use Regular Expressions :

In the following code sample, str1 and str2 are almost the same. I just inverted the position of '–' and '-' .

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
}

The character - you are searching for is different than the character in the text. Notice the length difference between the two.

The character present in the string is an en dash and is slightly wider than the hyphen (-) but narrower than the em dash (—). Due to this the contains function is not able to detect hyphen as en dash is present.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM