How Would You Count Occurrences of a String (Actually a Char) Within a String

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 to count of sub-string occurrences?

Regex.Matches(input, "OU=").Count

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", ".");

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.

find Count of Substring in string C#

Assume string is like this

string test = "word means collection of chars, and every word has meaning";

then just use regex to find how many times word is matched in your test string like this

int count = Regex.Matches(test, "word").Count;

output would be 2

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 == '&');

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: