Count the number of occurrences of a character in a string
str.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring
sub
in the range[start, end]
. Optional argumentsstart
andend
are interpreted as in slice notation.
>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4
How would you count occurrences of a string (actually a char) within a string?
If you're using .NET 3.5 you can do this in a one-liner with LINQ:
int count = source.Count(f => f == '/');
If you don't want to use LINQ you can do it with:
int count = source.Split('/').Length - 1;
You might be surprised to learn that your original technique seems to be about 30% faster than either of these! I've just done a quick benchmark with "/once/upon/a/time/" and the results are as follows:
Your original = 12s
source.Count = 19s
source.Split = 17s
foreach (from bobwienholt's answer) = 10s
(The times are for 50,000,000 iterations so you're unlikely to notice much difference in the real world.)
How do I count the number of occurrences of a char in a String?
My 'idiomatic one-liner' for this is:
int count = StringUtils.countMatches("a.b.c.d", ".");
Why write it yourself when it's already in commons lang?
Spring Framework's oneliner for this is:
int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");
Count the number of occurrences of a character in a string in Javascript
I have updated this answer. I like the idea of using a match better, but it is slower:
console.log(("str1,str2,str3,str4".match(/,/g) || []).length); //logs 3
console.log(("str1,str2,str3,str4".match(new RegExp("str", "g")) || []).length); //logs 4
Count the number of occurrences of characters in a string?
You keep overriding the key with the latest count in that comprehension. You would have to rather update them by addition:
data = "a1a3b5a2c4b1"
counts = {}
i = iter(data)
for char, count in zip(i, i):
counts[char] = counts.get(char, 0) + int(count)
# {'a': 6, 'b': 6, 'c': 4}
The other natural util to handle counts is, well, a collections.Counter
:
from collections import Counter
counts = Counter()
i = iter(data)
for char, count in zip(i, i):
counts.update(**{char: int(count)})
This also uses the "zip
the same iterator" trick to produce chunks of 2. AS for turning these dictionaries into the desired string output:
"".join(f"{k}{v}" for k, v in counts.items())
Count specific character occurrences in a string
The most straightforward is to simply loop through the characters in the string:
Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
Dim cnt As Integer = 0
For Each c As Char In value
If c = ch Then
cnt += 1
End If
Next
Return cnt
End Function
Usage:
count = CountCharacter(str, "e"C)
Another approach that is almost as effective and gives shorter code is to use LINQ extension methods:
Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
Return value.Count(Function(c As Char) c = ch)
End Function
Simple way to count character occurrences in a string
public int countChar(String str, char c)
{
int count = 0;
for(int i=0; i < str.length(); i++)
{ if(str.charAt(i) == c)
count++;
}
return count;
}
This is definitely the fastest way. Regexes are much much slower here, and possible harder to understand.
Number of occurrences of a character in a string
You could do this:
int count = test.Split('&').Length - 1;
Or with LINQ:
test.Count(x => x == '&');
Related Topics
Why Is It Impossible to Override a Getter-Only Property and Add a Setter
Namespace and Class with the Same Name
C# Get a Control's Position on a Form
Fields of Class, Are They Stored in the Stack or Heap
What Are the Benefits of Resource(.Resx) Files
ASP.NET Core Model Binding Error Messages Localization
How to Define a Method in Razor
Compare Two Lists for Differences
How to Run Multiple SQL Commands in a Single SQL Connection
One Class Per File Rule in .Net
Compile and Run Dynamic Code, Without Generating Exe
Comparing Timer with Dispatchertimer
ASP.NET Core Appsettings.JSON Update in Code
Wait Some Seconds Without Blocking UI Execution
What Does Maxdegreeofparallelism Do
Elevating Privileges Doesn't Work with Useshellexecute=False