Why is the containsKey() function not detecting the repeated char as the key in Dart in the problem below?

Viewed 29

The containsKey() function is not detecting the repeated value in my test 'current' string, where it just replaces the original value of the key 'r' with 3, when it should go through the containsKey() function, as see that there is a value at 2, and then replace that key with a new one.

void main(){
  Map<String, String> split = new Map();
  var word = 'current ';
  for (int i = 0; i < word.length; i++) {
    String temp = word[i];
    if (split.containsKey([temp])) {
      split[temp] = split[temp]! + ' ' + i.toString();
    } else {
      split[temp] = i.toString();
    }
  }
  print(split.toString());
}

The output produces {c: 0, u: 1, r: 3, e: 4, n: 5, t: 6} while I want it to produce {c: 0, u: 1, r: 2 3, e: 4, n: 5, t: 6}

1 Answers

It is because you are doing split.containsKey([temp]) instead of split.containsKey(temp). In your snippet, you are checking whether the map split has the array [temp] as a key, (in the case of 'r': ['r']), which is false, it has 'r' as a key, not ['r'].

Change your code to

void main(){
  Map<String, String> split = new Map();
  var word = 'current ';
  for (int i = 0; i < word.length; i++) {
    String temp = word[i];
    if (split.containsKey(temp)) {  // <- Change here.
      split[temp] = split[temp]! + ' ' + i.toString();
    } else {
      split[temp] = i.toString();
    }
  }
  print(split.toString());
}
Related