mian.mubeen ahmed
mian.mubeen ahmed

Reputation: 21

Function to find the duplicate characters in a string with their number of occurrences in the Dart language

How can we find duplicate characters in a string with their number of occurrences? The function should be generic in the Dart language.

Sample:

Input = “abcBCAacd”

Output = “a”: 3
“B” : 2 , “c” :3

Upvotes: 0

Views: 4176

Answers (3)

Randal Schwartz
Randal Schwartz

Reputation: 44091

I had to presume you wanted the d counted, and that everything should be folded to lowercase. If B and b are in different buckets, just remove the toLowerCase() from below:

void main() {
  var input = 'abcBCAacd';
  var chars = input.toLowerCase().split('');
  var counts = <String, int>{};
  for (var char in chars) {
    counts[char] = (counts[char] ?? 0) + 1;
  }
  print(counts);
}

Upvotes: 1

Sami TOUIBI
Sami TOUIBI

Reputation: 1

void main() {
  
  int nbOccurence = 0;
  String input ="abcdeffff";
   for( var i = 0 ; i < input.length; i++ ) { 
     nbOccurence = 0;
      for( var j = 0 ; j < input.length; j++ ) {
        if (input[i] == input[j]){
          nbOccurence++;
        }
      }
     print(input[i] + ":" + nbOccurence.toString());
   }
  
}

Upvotes: 0

void main(List<String> args) {
  var input = 'abcBCAacd'.toLowerCase().split('');
  var list1 = input.toSet();
  var myMap = Map<String, int>.fromIterables(list1, List.generate(list1.length, (i) => 0));
  input.forEach((e) => myMap[e] = myMap[e]! + 1);
  print(myMap);
}

Result:

{a: 3, b: 2, c: 3, d: 1}

Upvotes: 1

Related Questions