你将如何计算一个字符串中的字符串的出现? [英] How would you count occurrences of a string within a string?

查看:126
本文介绍了你将如何计算一个字符串中的字符串的出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做的事情,我意识到,我想看看有多少 / 我所能在一个字符串中找到,然后把它打动了我,这有几种方法做到这一点,但什么是最好的(或最简单的)是不能决定。

目前,我喜欢的东西去:

 字符串源=/次/时/年/时间/;
诠释计数= source.Length - source.Replace(/,)。长度;

但我不喜欢它,任何考生?

我真的不希望挖掘出的正则表达式这一点,是吧?

我知道我的字符串都将有这个词我在寻找,这样你就可以假定...

课程字符串长度的地方> 1

 字符串草垛=/次/时/年/时间;
串针=/;
INT needleCount =(haystack.Length - source.Replace(针,)长度)/ needle.Length


解决方案

如果您正在使用.NET 3.5,你可以在一个班轮与LINQ做到这一点:

 诠释计数= source.Count(F =>˚F=='/');

如果你不想使用LINQ你可以做到这一点:

 诠释计数= source.Split('/')长度 -  1。


您可能会惊讶地得知,原来的技术似乎比其中任一快约30%!我只是做了一个快速的基准用/次/时/年/时间/,结果如下:


  

您最初的12秒=结果
  source.Count = 19S结果
  source.Split = 17S结果
  的foreach(从bobwienholt的回答 )= 10S


(该时间是50,000,000迭代因此你不太可能注意到在现实世界太大的区别。)

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 - source.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.)

这篇关于你将如何计算一个字符串中的字符串的出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆