Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

c# - 您如何计算字符串中字符串(实际上是字符)的出现?(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?

(我真的不想为此挖掘RegEx ,对吗?)

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 ,

(当然,对于其中的字符串长度> 1,)

string haystack = "/once/upon/a/time";
string needle = "/";
int needleCount = ( haystack.Length - haystack.Replace(needle,"").Length ) / needle.Length;
  ask by inspite translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!

(您可能会惊讶地发现您的原始技术似乎比这两种技术都快30%!)

I've just done a quick benchmark with "/once/upon/a/time/" and the results are as follows:

(我刚刚使用“ / once / upon / a / time /”做了一个快速基准测试,结果如下:)

Your original = 12s

(你原来的= 12秒)
source.Count = 19s

(source.Count = 19秒)
source.Split = 17s

(source.Split = 17秒)
foreach ( from bobwienholt's answer ) = 10s

(foreach( 根据bobwienholt的回答 )= 10s)

(The times are for 50,000,000 iterations so you're unlikely to notice much difference in the real world.)

((时间是进行5000万次迭代,因此您不太可能注意到现实世界中的巨大差异。))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...