How would you count occurrences of a string (actually a char) within a string?(您将如何计算字符串中字符串(实际上是字符)的出现次数?)
问题描述
I am doing something where I realised I wanted to count how many /
s I could find in a string, and then it struck me, that there were several ways to do it, but couldn't decide on what the best (or easiest) was.
At the moment I'm going with something like:
string source = "/once/upon/a/time/";
int count = source.Length - source.Replace("/", "").Length;
But I don't like it at all, any takers?
I don't really want to dig out RegEx
for this, do I?
I know my string is going to have the term I'm searching for, so you can assume that...
Of course for strings where length > 1,
string haystack = "/once/upon/a/time";
string needle = "/";
int needleCount = ( haystack.Length - haystack.Replace(needle,"").Length ) / needle.Length;
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.)
这篇关于您将如何计算字符串中字符串(实际上是字符)的出现次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:您将如何计算字符串中字符串(实际上是字符)的出现次数?


- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01