字符串匹配算法之BF算法
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BK { class Program { static void Main(string[] args) { Console.WriteLine(BF("abcdef", "abce")); Console.WriteLine(BF("abcdef", "ab")); Console.WriteLine(BF("abcdef", "bc")); Console.WriteLine(BF("abcdef", "cd")); Console.WriteLine(BF("abcdef", "de")); Console.WriteLine(BF("abcdef", "ef")); Console.WriteLine(BF("abcdef", "ef3")); Console.ReadKey(); } private static int BF(string resStr, string pStr) { int result = -1; int resStrLength = resStr.Length; int pStrLength = pStr.Length; int i = 0, j = 0; while (i < resStrLength && j < pStrLength) { if (resStr[i] == pStr[j]) { i++; j++; } else { i = i - j + 1; j = 0; } } if (j >= pStrLength) { result = i - j; } return result; } } }
运算结果: