Click here to Skip to main content
15,879,095 members
Articles / Programming Languages / C#

An extensible math expression parser with plug-ins

Rate me:
Please Sign up or sign in to vote.
4.92/5 (147 votes)
13 Mar 2008CPOL51 min read 1.4M   29K   364  
Design and code for an extensible, maintainable, robust, and easy to use math parser.
#include "MTCommon.h"
#include <windows.h>

bool findSubStr(const MTSTRING &str, const MTSTRING &subStr)
{
	int strLength = str.size();
	int subStrLength = subStr.size();

	if( subStrLength > strLength )
	{
		return false;	
	}

	int end = strLength - subStrLength;

	for( int t=0; t<=end; t++ )
	{
		if( isStrBegin(str.c_str()+t, subStr.c_str(), strLength-t, subStrLength ) )
		{
			return true;
		}

	}

	return false;
}

bool isStrBegin(const MTCHAR *str, const MTCHAR *beginStr, int strLength, int beginStrLength)
{
	if( strLength == -1 )
	{
		strLength = lstrlen(str);
	}

	if( beginStrLength == -1 )
	{
		beginStrLength = lstrlen(beginStr);
	}
	
	if( beginStrLength > strLength )
	{
		return false;	// impossible to find a substring that is lengthier than the string itself!
	}

	for(int pos=0; pos < beginStrLength; pos++ )
	{
		if( str[pos] != beginStr[pos] )
		{
			return false;	// no match...!
		}
	}

	return true;	// match!

}

// check if this word contains only numerical characters
bool isOnlyNum(const MTCHAR *word, const MTCHAR &decimalPoint)
{	
	unsigned int length = lstrlen(word);
	bool decimal = false;	// indicate if a decimal point character has been encountered
							// at most it can only have one decimal point character
							// else, this is not a numerical only string

	for( unsigned int t=0; t<length; t++ )
	{
		// if this is not a numeric character and not the decimal point character
		if( !MTISDIGIT(word[t]) && word[t] != decimalPoint )
		{
			return false;	// alpha or special character
		}

		if( word[t] == decimalPoint )
		{
			if( decimal )
			{
				return false;	// a second decimal point character! 			
			}
			else
			{
				decimal = true;
			}

		}
			

	}

	return true;
}

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Canada Canada
Software Engineer working at a fun and smart startup company

Comments and Discussions