C# 我的代码在第一次匹配时停止,我需要搜索整个文本
看起来这里有问题,但我找不到第一场比赛后如何继续搜索。我需要做一个Horspool算法a的程序,我被困在那里了。它应该搜索所有文本,但当第一次匹配时,它会停止C# 我的代码在第一次匹配时停止,我需要搜索整个文本,c#,algorithm,loops,search,C#,Algorithm,Loops,Search,看起来这里有问题,但我找不到第一场比赛后如何继续搜索。我需要做一个Horspool算法a的程序,我被困在那里了。它应该搜索所有文本,但当第一次匹配时,它会停止 public static class BoyerMooreHorspool { public static int Find(string haystack, string needle) { // If substring is bigger than string, no match exists
public static class BoyerMooreHorspool
{
public static int Find(string haystack, string needle)
{
// If substring is bigger than string, no match exists
if (needle.Length > haystack.Length)
return -1;
// If the substring has characters not in the string, no match exists
if (needle.Except(haystack).Any())
return -1;
Dictionary<char, int> BadMatchTable = new Dictionary<char, int>();
// Initializes every letter with the default value
foreach (char c in haystack)
{
if (!BadMatchTable.Keys.Contains(c))
BadMatchTable.Add(c, needle.Length);
}
// The formula for every letter in the needle (except the last) is lenght - index - 1
for (int i = 0; i < needle.Length - 1; i++)
{
BadMatchTable[needle[i]] = needle.Length - i - 1;
}
int index = 0;
while (index <= haystack.Length - needle.Length)
{
bool match = true;
for (int i = needle.Length - 1; i >= 0; i--)
{
if (needle[i] != haystack[index + i])
{
match = false;
index = index + BadMatchTable[haystack[index + needle.Length - 1]];
}
}
if (match)
{
return index;
}
if (index==haystack.Length)
{
return -1;
}
}
return -1;
}
}
公共静态类BoyerMooreHorspool
{
公共静态int-Find(字符串干草堆、字符串针)
{
//如果子字符串大于字符串,则不存在匹配项
if(针.长度>干草堆.长度)
返回-1;
//如果子字符串中没有字符,则不存在匹配项
if(针.除(干草堆).Any()外)
返回-1;
Dictionary BadMatchTable=新字典();
//用默认值初始化每个字母
foreach(干草堆中的碳)
{
如果(!BadMatchTable.Keys.Contains(c))
BadMatchTable.添加(c,针.长度);
}
//针中每个字母(最后一个除外)的公式为lenght-index-1
对于(int i=0;i
而不是
return index;
试一试
它这样做是因为在第一次匹配时返回一个值<代码>返回索引将停止循环的执行,并将值返回给
Find
方法调用方。您能告诉我们您期望的返回值吗?是的,但当我尝试更改此值时,它会无休止地返回loop@Stefan我要在干草堆里找到所有的火柴,total compare number和total match number首先我尝试定义一个列表并将匹配索引添加到此列表,但没有成功。谢谢,但我收到了以下错误消息:CS1622无法从迭代器返回值。使用yield return语句返回值,或使用yield break语句终止迭代。此外,此错误CS1624“BoyerMooreHorspool.Find(string,string)”不能是迭代器块,因为“int”不是迭代器接口的类型
yield return index;