Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should use the update function like this:

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

occurence(text){
  var words = text.split(" ");
  print(words);
  var count = {};
  for (var word in words) {
      count.update(word, (value) => value + 1, ifAbsent: () => 1);
  }
  return count;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading