Home >Backend Development >C++ >What's the Fastest Way to Count String Occurrences in .NET?

What's the Fastest Way to Count String Occurrences in .NET?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-31 06:41:07302browse

What's the Fastest Way to Count String Occurrences in .NET?

The best way to count the string count

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
  • Source.Count: 19 seconds
  • Source.split: 17 seconds
  • Foreach loop (from other answers): 10 seconds
  • Although these time differences may not be obvious in practical applications, the original character replacement method is still the fastest for this situation.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn