Click here to Skip to main content
15,881,793 members
Articles / Mobile Apps

Tolerant string matching using the Levenshtein algorithm

Rate me:
Please Sign up or sign in to vote.
2.10/5 (17 votes)
29 Apr 20052 min read 50.9K   648   20  
A practical example how to use the Levenshtein algorithm for string matching
// Levenshtein.h: interface for the Levenshtein class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(LEVENSHTEIN_H)
#define LEVENSHTEIN_H

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

class Levenshtein  
{
public:
	int Get  (const char* a, const char* b);
	int Get  (const char* a, int aLen, const char* b, int bLen);

    int Get2 (char const *s, char const *t);
    int Get2 (char const *s, int n, char const *t, int m);
	
	Levenshtein();
	virtual ~Levenshtein();


private:
	//****************************
	// Get minimum of three values
	//****************************
    int Minimum (int a, int b, int c)
	{
		int mi = a;
		
		if (b < mi)		mi = b;
		if (c < mi)		mi = c;
		
		return mi;
	}

	//**************************************************
	// Get a pointer to the specified cell of the matrix
	//**************************************************
    int *GetCellPointer (int *pOrigin, int col, int row, int nCols)
	{ return pOrigin + col + (row * (nCols + 1)); }
    
	//*****************************************************
	// Get the contents of the specified cell in the matrix
	//*****************************************************
	int GetAt (int *pOrigin, int col, int row, int nCols)
	{
		int *pCell = GetCellPointer (pOrigin, col, row, nCols);
		return *pCell;
	}
	
	//********************************************************
	// Fill the specified cell in the matrix with the value x
	//********************************************************
	void PutAt (int *pOrigin, int col, int row, int nCols, int x)
	{
		int *pCell = GetCellPointer (pOrigin, col, row, nCols);
		*pCell = x;
	}
};

#endif // !defined(AFX_LEVENSHTEIN_H__1652E861_359D_11D6_BB45_000102A63CA4__INCLUDED_)

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions