C# 您将如何计算字符串中字符串(实际上是一个字符)的出现次数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/541954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How would you count occurrences of a string (actually a char) within a string?
提问by inspite
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.
我正在做一些事情,我意识到我想计算/
我可以在字符串中找到多少个s,然后我突然想到,有几种方法可以做到,但无法决定最好(或最简单)的方法是什么.
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?
我真的不想为此挖苦RegEx
,是吗?
I know my string is going to have the term I'm searching for, so you can assume that...
我知道我的字符串将包含我正在搜索的术语,因此您可以假设...
Of course for strings wherelength > 1,
当然对于串的其中长度> 1,
string haystack = "/once/upon/a/time";
string needle = "/";
int needleCount = ( haystack.Length - haystack.Replace(needle,"").Length ) / needle.Length;
采纳答案by LukeH
If you're using .NET 3.5 you can do this in a one-liner with LINQ:
如果您使用 .NET 3.5,您可以使用 LINQ 在单行中执行此操作:
int count = source.Count(f => f == '/');
If you don't want to use LINQ you can do it with:
如果你不想使用 LINQ,你可以这样做:
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:
您可能会惊讶地发现,您的原始技术似乎比其中任何一种都快 30%!我刚刚用“/once/upon/a/time/”做了一个快速基准测试,结果如下:
Your original = 12s
source.Count = 19s
source.Split = 17s
foreach (from bobwienholt's answer) = 10s
您原来的 = 12s source.Count
= 19s
source.Split = 17s
foreach(来自 bobwienholt 的回答)= 10s
(The times are for 50,000,000 iterations so you're unlikely to notice much difference in the real world.)
(时间为 50,000,000 次迭代,因此您不太可能注意到现实世界中的太大差异。)
回答by bobwienholt
string source = "/once/upon/a/time/";
int count = 0;
foreach (char c in source)
if (c == '/') count++;
Has to be faster than the source.Replace()
by itself.
必须比source.Replace()
它本身更快。
回答by Judah Gabriel Himango
LINQ works on all collections, and since strings are just a collection of characters, how about this nice little one-liner:
LINQ 适用于所有集合,并且由于字符串只是字符的集合,那么这个漂亮的小单行怎么样:
var count = source.Count(c => c == '/');
Make sure you have using System.Linq;
at the top of your code file, as .Count
is an extension method from that namespace.
确保您using System.Linq;
在代码文件的顶部,以及.Count
来自该命名空间的扩展方法。
回答by ZombieSheep
These both only work for single-character search terms...
这些都只适用于单字符搜索词...
countOccurences("the", "the answer is the answer");
int countOccurences(string needle, string haystack)
{
return (haystack.Length - haystack.Replace(needle,"").Length) / needle.Length;
}
may turn out to be better for longer needles...
对于更长的针头可能会更好......
But there has to be a more elegant way. :)
但必须有更优雅的方式。:)
回答by mqp
If you want to be able to search for whole strings, and not just characters:
如果您希望能够搜索整个字符串,而不仅仅是字符:
src.Select((c, i) => src.Substring(i))
.Count(sub => sub.StartsWith(target))
Read as "for each character in the string, take the rest of the string starting from that character as a substring; count it if it starts with the target string."
读作“对于字符串中的每个字符,将从该字符开始的字符串的其余部分作为子字符串;如果它以目标字符串开头,则计算它。”
回答by Brian Rudolph
Edit:
编辑:
source.Split('/').Length-1
回答by Yet Another Code Maker
int count = new Regex(Regex.Escape(needle)).Matches(haystack).Count;
回答by preetham
string s = "65 fght 6565 4665 hjk";
int count = 0;
foreach (Match m in Regex.Matches(s, "65"))
count++;
回答by Ben
private int CountWords(string text, string word) {
int count = (text.Length - text.Replace(word, "").Length) / word.Length;
return count;
}
Because the original solution, was the fastest for chars, I suppose it will also be for strings. So here is my contribution.
因为原始解决方案对于字符来说是最快的,所以我想它也适用于字符串。所以这是我的贡献。
For the context: I was looking for words like 'failed' and 'succeeded' in a log file.
对于上下文:我在日志文件中寻找诸如“失败”和“成功”之类的词。
Gr, Ben
Gr, 本
回答by Richard Watson
string source = "/once/upon/a/time/";
int count = 0;
int n = 0;
while ((n = source.IndexOf('/', n)) != -1)
{
n++;
count++;
}
On my computer it's about 2 seconds faster than the for-every-character solution for 50 million iterations.
在我的计算机上,它比 5000 万次迭代的 for-every-character 解决方案快约 2 秒。
2013 revision:
2013年修订:
Change the string to a char[] and iterate through that. Cuts a further second or two off the total time for 50m iterations!
将字符串更改为 char[] 并遍历它。将 50m 迭代的总时间再缩短一两秒!
char[] testchars = source.ToCharArray();
foreach (char c in testchars)
{
if (c == '/')
count++;
}
This is quicker still:
这仍然更快:
char[] testchars = source.ToCharArray();
int length = testchars.Length;
for (int n = 0; n < length; n++)
{
if (testchars[n] == '/')
count++;
}
For good measure, iterating from the end of the array to 0 seems to be the fastest, by about 5%.
为了更好地衡量,从数组末尾迭代到 0 似乎是最快的,大约 5%。
int length = testchars.Length;
for (int n = length-1; n >= 0; n--)
{
if (testchars[n] == '/')
count++;
}
I was wondering why this could be and was Googling around (I recall something about reverse iterating being quicker), and came upon this SO question which annoyingly uses the string to char[] technique already. I think the reversal trick is new in this context, though.
我想知道为什么这可能并且正在谷歌搜索(我记得一些关于反向迭代更快的事情),并遇到了这个问题,它已经烦人地使用字符串到字符 [] 技术。不过,我认为在这种情况下逆转技巧是新的。
What is the fastest way to iterate through individual characters in a string in C#?