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
Release: 2025-01-31 06:41:07
Original
383 people have browsed it

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:
string source = "/once/upon/a/time/";
int count = source.Length - source.Replace("/", "").Length;
Copy after login

But for the .NET 3.5 users, the more concise and efficient solution was to use Linq:
string haystack = "/once/upon/a/time/";
string needle = "/";
int needleCount = (haystack.Length - haystack.Replace(needle, "").Length) / needle.Length;
Copy after login

or, you can choose:
int count = source.Count(f => f == '/');
Copy after login

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:
int count = source.Split('/').Length - 1;
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template