【发布时间】:2021-01-08 21:09:08
【问题描述】:
我正在尝试使用蛮力技术进行简单的子字符串搜索,但出现错误。我对编程很陌生,所以请记住这一点。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace Csharp_Training
{
class Program
{
public static int Search(string Text, string Pattern,int N, int M)
{
for (int i = 0; i < N - M; i++)
{
int j;
for (j = 0; j < M; j++)
{
if (Text[i + j] != Pattern[i])
{
break;
}
if (j == M) return i;
}
}
return N;
}
static void Main(string[] args)
{
string Txt = "this is a test";
string Pttrn = "test";
int LN = Txt.Length;
int LM = Pttrn.Length;
int result = Search(Txt, Pttrn, LN, LM);
Console.Write(result);
}
}
}
【问题讨论】:
-
尝试使用 SubString 方法:docs.microsoft.com/en-us/dotnet/api/…
-
for (j = 0; j < M; ... if (j == M),if 条件永远不会为真,因为j<M -
这能回答你的问题吗? Simple substring search (brute force)
-
if (j == M)行需要在循环之后。在循环内部,条件永远不会为真。循环后,如果模式匹配文本,则为真。 -
还要注意条件
i < N - M应该是i <= N - M。否则,当它位于文本末尾时,您将找不到该模式。例如 text="abc" N=3,和 pattern="bc" M=2。i < N - M表示i < 1只会根据索引 0 检查模式,而实际上模式将在索引 1 处匹配。
标签: c# algorithm search substring brute-force