算法没什么可说的,就是一段一段匹配呗。
运行效果:
源代码:
using System;
using System.Collections;
using System.Collections.Generic;
namespace Legalsoft.Truffer.Algorithm
{
/// <summary>
/// 字符串匹配(模式搜索)算法集锦
/// </summary>
public static partial class PatternSearch
{
/// <summary>
/// 字符串匹配的暴力算法(1)
/// </summary>
/// <param name="text"></param>
/// <param name="pattern"></param>
/// <returns></returns>
public static List<int> NativeSearch_Original(string text, string pattern)
{
int pt = pattern.Length;
List<int> matchs = new List<int>();
for (int i = 0; i < (text.Length - pt); i++)
{
if (text.Substring(i, pt) == pattern)
{
matchs.Add(i);
}
}
return matchs;
}
/// <summary>
/// 字符串匹配的暴力算法(2)
/// </summary>
/// <param name="text"></param>
/// <param name="pattern"></param>
/// <returns></returns>
public static List<int> Native_Search(string text, string pattern)
{
List<int> matchs = new List<int>();
int M = pattern.Length;
int N = text.Length;
int S = N - M;
if (S <= 0) return matchs;
for (int i = 0; i <= S; i++)
{
int j = 0;
while (j < M)
{
if (text[i + j] != pattern[j])
{
break;
}
j++;
}
if (j == M)
{
matchs.Add(i);
}
}
return matchs;
}
}
}
--------------================--------------------
POWER BY TRUFFER.CN
using System;
using System.Collections;
using System.Collections.Generic;
namespace Legalsoft.Truffer.Algorithm
{
/// <summary>
/// 字符串匹配(模式搜索)算法集锦
/// </summary>
public static partial class PatternSearch
{
/// <summary>
/// 字符串匹配的暴力算法(1)
/// </summary>
/// <param name="text"></param>
/// <param name="pattern"></param>
/// <returns></returns>
public static List<int> NativeSearch_Original(string text, string pattern)
{
int pt = pattern.Length;
List<int> matchs = new List<int>();
for (int i = 0; i < (text.Length - pt); i++)
{
if (text.Substring(i, pt) == pattern)
{
matchs.Add(i);
}
}
return matchs;
}
/// <summary>
/// 字符串匹配的暴力算法(2)
/// </summary>
/// <param name="text"></param>
/// <param name="pattern"></param>
/// <returns></returns>
public static List<int> Native_Search(string text, string pattern)
{
List<int> matchs = new List<int>();
int M = pattern.Length;
int N = text.Length;
int S = N - M;
if (S <= 0) return matchs;
for (int i = 0; i <= S; i++)
{
int j = 0;
while (j < M)
{
if (text[i + j] != pattern[j])
{
break;
}
j++;
}
if (j == M)
{
matchs.Add(i);
}
}
return matchs;
}
}
}