Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# c中计算另一个字符串中字符串出现次数的最快方法#_C# - Fatal编程技术网

C# c中计算另一个字符串中字符串出现次数的最快方法#

C# c中计算另一个字符串中字符串出现次数的最快方法#,c#,C#,我必须在一个非常长的字符串(大约30mb的纯文本)中计算字符串出现的次数 我现在使用以下代码: int count=new Regex(Regex.Escape(stringthatiamlooking)).Matches(stringToSearchIn.count 但是它太慢了。在i7和16gb ram上大约需要3分钟。 示例数据为: 43.996442,-31.768039 43.996432,-31.768039 43.996432,-31.768049 43.996422,-31.76

我必须在一个非常长的字符串(大约30mb的纯文本)中计算字符串出现的次数 我现在使用以下代码:
int count=new Regex(Regex.Escape(stringthatiamlooking)).Matches(stringToSearchIn.count
但是它太慢了。在i7和16gb ram上大约需要3分钟。
示例数据为:

43.996442,-31.768039
43.996432,-31.768039
43.996432,-31.768049
43.996422,-31.768049
43.996422,-31.768059
我想数数(例如)
.7
有比regeex更快的方法吗

好的,解决了 到目前为止最快的函数是:(我只需要检查两个字符。)

public int countoccurrences2(字符串源,char charOne,charTwo)
{
整数计数=0;
对于(int i=0;i,从这个问题:

以下代码似乎是性能最好的:

int count = 0, n = 0;

if(substring != "")
{
    while ((n = source.IndexOf(substring, n, StringComparison.InvariantCulture)) != -1)
    {
        n += substring.Length;
        ++count;
    }
}

Richard Watson在上述问题中提供的解决方案

将字符串转换为字节数组并通过简单的for循环查找正确的两个数字需要多长时间?有时,低技术的方法并不是最糟糕的。可能的重复请让我们知道每个解决方案的性能。对于科学!:DHOLY CRAP,SimonRiboldi的答案大约比regex快10倍。请注意,被接受的答案和实际上大多数答案在计算字符时都是完全错误的;还请注意,任何Linq解决方案都会因大字符串而出现故障!这是我在SOYes上见过的投票测量出错的最糟糕的例子,可能是因为指针太短了。我做了测试that’去年,当needle和haystack grow regex最终获胜时。@太好了,太好了!我们总是需要这种函数,了解每种方法的缺点非常有用。我还可以补充一点,由于Unicode的考虑,任何基于简单字节比较的比较都会在某些情况下给出错误的答案ata,所以使用这样一个尊重Unicode的方法是一个明确的加号。我认为这个答案(可以说)是错误的,因为“n+=substring.Length”行-如果在字符串“abcabca”中搜索“abca”,那么它只会在(可以说)应该返回2时返回1。
int count = 0, n = 0;

if(substring != "")
{
    while ((n = source.IndexOf(substring, n, StringComparison.InvariantCulture)) != -1)
    {
        n += substring.Length;
        ++count;
    }
}