Peter
Peter

Reputation: 1919

How can I count the number of a letter in a string using Dart?

I'm trying to calculate how many of the letter a I have in the sentence: Hello Jordania.

I found the function contains(). I'm using it like this:

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

As we know, I got True as a response. I couldn't find the right function to calculate how many times I get an a. I might be able to do something with a loop if I can check every single character? I'm lost on this.

Upvotes: 33

Views: 31250

Answers (6)

Mithun Adhikari
Mithun Adhikari

Reputation: 569

Probably not the best one, but you can also do something like this.

void main() {
  var a = "ht://adfd//.coma/";

  int count = a.split("t").length - 1;
  print(count);
}

You will need to subtract 1 because it is splitting into a list first and then counting the size of that list.

Upvotes: 3

Tippu Venky
Tippu Venky

Reputation: 49

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);
}

Upvotes: 4

Kai Sellgren
Kai Sellgren

Reputation: 30222

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.

Upvotes: 89

Peter
Peter

Reputation: 1919

void main() {
  const regExp = const RegExp("a");
  print(regExp.allMatches("Hello Jordania").length); // 2
}

Upvotes: 6

ARA
ARA

Reputation: 1316

  // count letters
  Map<int,int> counts = new Map<int,int>();
  for (var c in s.charCodes() ) {
    counts[c] = counts.putIfAbsent(c, p()=>0) + 1;
  }
  // print counts
  for (var c in counts.getKeys())
    print("letter ${new String.fromCharCodes([c])} count=${counts[c]}");

Upvotes: -1

Justin Fagnani
Justin Fagnani

Reputation: 11171

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
}

Upvotes: 2

Related Questions