RSS

KMP String Searching Algorithm in C#

Wed, Dec 9, 2009

Inverview Tips, Programming, Tutorials

We’ve C# example of KMP (Knuth–Morris–Pratt) string serching algorithm.

/// <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:

static void Main(string[] args)
{
	int foundPosition=SearchKMP("eXclusiveMinds".ToCharArray() ,"01eXclusiveMinds".ToCharArray() );
	Console.WriteLine(foundPosition);
}

OUTPUT:

String Found at index: 2
Sharing ~ Helping Other:
  • Print
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • BlinkList
  • DZone
  • Slashdot
  • YahooMyWeb
  • StumbleUpon
  • Live
  • IndianPad
  • DotNetKicks
  • Technorati

Related Posts:

, ,

This post was written by:

eXclusiveMinds - who has written 500 posts on eXclusiveMinds.


Contact the author

2 Comments For This Post

  1. chota Says:

    this is really gr8 algorithm.This site has helped me a lot to prepare for my interview. Thanks a lot to admin!

  2. overred Says:

    This is not KMP algorithm!
    And has a big bug….
    if search string is “aabac” and main string is “aabaabac”,you will lost…
    link:http://www.cnblogs.com/overred/archive/2009/06/13/badwordparser.html

Leave a Reply

You must be logged in to post a comment.