Home >Backend Development >C++ >What's the Fastest Way to Count String Occurrences in .NET?
Find all the number of times in the specific character or sub -string in a given string in a .NET. There are many ways to appear. This article focuses on the most effective and convenient method, especially when the slash (/) in the statistical string.
First of all, you can consider using character replacement, for example:
Or, for a sub -string with a length of more than one character, you can use:
<code class="language-csharp">string source = "/once/upon/a/time/"; int count = source.Length - source.Replace("/", "").Length;</code>
But for the .NET 3.5 users, the more concise and efficient solution was to use Linq:
<code class="language-csharp">string haystack = "/once/upon/a/time/"; string needle = "/"; int needleCount = (haystack.Length - haystack.Replace(needle, "").Length) / needle.Length;</code>
or, you can choose:
<code class="language-csharp">int count = source.Count(f => f == '/');</code>
Surprisingly, the initial character removal method is about 30%faster than the Linq or Split method. The benchmark test of the string "/ONCE/Upon/A/Time/" generates the following chronograph results:
<code class="language-csharp">int count = source.Split('/').Length - 1;</code>
Character replacement method: 12 seconds
The above is the detailed content of What's the Fastest Way to Count String Occurrences in .NET?. For more information, please follow other related articles on the PHP Chinese website!