算法没什么可说的,就是一段一段匹配呗。
运行效果:
源代码:
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;
}
}
}
--------------================--------------------文章来源:https://www.toymoban.com/news/detail-790463.html
POWER BY TRUFFER.CN文章来源地址https://www.toymoban.com/news/detail-790463.html
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;
}
}
}
到了这里,关于C#,字符串匹配(模式搜索)原生(Native)算法的源代码的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!