We’ve C# example of KMP (Knuth–Morris–Pratt) string serching algorithm.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | /// <summary> /// C# Implementation of KMP Algorithm /// </summary> /// <param name="w">Search String</param> /// <param name="s">Main String</param> /// <returns></returns> public int SearchKMP(char[] w, char[] s) { int m = 0; int i = 0; int[] t = new int[w.Length]; while (((m + i) < s.Length) && (i < w.Length)) { if (s[m + i] == w[i]) i++; else { m += i - t[i]; if (i > 0) i = t[i]; i++; } } if (i == w.Length) return m; else return -1; } |
Testing it:
1 2 3 4 5 | static void Main(string[] args) { int foundPosition=SearchKMP("eXclusiveMinds".ToCharArray() ,"01eXclusiveMinds".ToCharArray() ); Console.WriteLine(foundPosition); } |
OUTPUT:
String Found at index: 2 |

January 19th, 2010 at 12:37 pm
this is really gr8 algorithm.This site has helped me a lot to prepare for my interview. Thanks a lot to admin!