Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate number of a letter in a string using Dart

I try to calculate how many letter "a" i have in the sentence: "Hello Jordania".

I find the function contains. I using it like this:

  var phrase = "Hello Jordania;
  var comptenbrdea = phrase.contains('a');
  print(comptenbrdea);

I get "True" as response. Normal you will say, I know, but I dont find the right function to calculate how many time i get an a. I can maybe do something with a loop if I can check every single character? ... I'm lost on http://www.dartlang.org/search.html?cx=011220921317074318178%3Ai4mscbaxtru&ie=UTF-8&hl=en&q=string_scanner ... Can some one help me ?

like image 697
Peter Avatar asked Oct 28 '12 16:10

Peter


4 Answers

Here's a simple way to do it:

void main() {
  print('a'.allMatches('Hello Jordania').length); // 2
}

Edit: the tested string is the parameter, not the character to be counted.

like image 113
Kai Sellgren Avatar answered Oct 21 '22 12:10

Kai Sellgren


void main(){
  String str = "yours string";
  Map<String, int> map = {};
  for(int i = 0; i < str.length; i++){
    int count = map[str[i]] ?? 0;
     map[str[i]] = count + 1;
  }
  print(map);
}
like image 34
Tippu Venky Avatar answered Oct 21 '22 11:10

Tippu Venky


void main() {
  const regExp = const RegExp("a");
  print(regExp.allMatches("Hello Jordania").length); // 2
}
like image 20
Peter Avatar answered Oct 21 '22 10:10

Peter


You need to iterate on the characters and count them, you comment above contains a general function for building a histogram, but the version that just counts 'a's is probably good for you to write. I'll just show you how to loop over characters:

var myString = "hello";
for (var char in myString.splitChars()) {
  // do something
}
like image 28
Justin Fagnani Avatar answered Oct 21 '22 11:10

Justin Fagnani