Ayz
Ayz

Reputation: 309

How to count the occurence of each word from the string? Dart

void main (){
  print(occurence("hello hi hello one two two three"));
}

occurence(text){
  var words = text.split(" ");
  print(words);
  var count = {};
  words.map((element) => {
    if (count[element]){
      count[element]+=1
    }else{
     count[element] =1
      }
  });
  return count;
}

I want to get this output: {hello:2, hi:1, one:1, two:2, three:1}

Where's the problem in my code, I just get {} when I run the program.

Upvotes: 1

Views: 692

Answers (1)

VincentDR
VincentDR

Reputation: 709

You should use the update function like this:

void main() {
  print(occurence("hello hi hello one two two three"));
  // {hello: 2, hi: 1, one: 1, two: 2, three: 1}
}

Map<String, int> occurence(String text) {
  List<String> words = text.split(" ");
  print(words); // [hello, hi, hello, one, two, two, three]

  Map<String, int> count = {};
  for (var word in words) {
    count.update(word, (value) => value + 1, ifAbsent: () => 1);
  }

  return count;
}

Upvotes: 3

Related Questions