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:
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
Related Topics
There Is Already an Open Datareader Associated With This Command Which Must Be Closed First
What Are Regular Expression Balancing Groups
JavaScriptserializer - Json Serialization of Enum as String
Difference Between Const and Readonly in C#
Dynamic Linq Orderby on Ienumerable≪T≫/Iqueryable≪T≫
Convert Utc/Gmt Time to Local Time
Why Is Thread.Sleep So Harmful
Pass an Instantiated System.Type as a Type Parameter For a Generic Class
How to Get a User'S Client Ip Address in Asp.Net
C# Datetime to "Yyyymmddhhmmss" Format
How to Start a Process from C#
How to Save a Stream to a File in C#
Async/Await VS Backgroundworker
How to Detect Windows 64-Bit Platform With .Net