Hmm... this post seems to have gotten lost. Reposting.
There are two ways to look at this problem.
First, perhaps the "variables" in the expression are always named "pay"
followed by a digit. You could use a regular expression to find them,
and then substitute their values for them.
However, this raises the larger question of where are you going to find
their values?
The other way to look at the problem is to decide first where to store
the values. I would suggest a Hashtable, where the variable names are
the keys and the entries are the values. Then all you do is go through
the string, looking for identifiers, and when you find one that is in
the Hashtable, subustitute the corresponding value.
Basically, the algorithm goes like this:
// Fill a Hashtable with variables and corresponding values
Hashtable variables = new Hashtable();
variables["pay1"] = 45.6;
variables["pay6"] = 100.2;
etc.
// Build up a new string with the same expression as the expression
string,
// but with the variables replaced by their values
string expression = "(pay1 * pay6) * 20 / 100";
StringBuilder outExpression = new StringBuilder();
Regex identifierRegex = new Regex("[a-zA-Z][a-zA-Z0-9]*");
int inputIndex = 0;
Match nextIdMatch = identifierRegex.Match(expression, inputIndex);
while (nextIdMatch.Success)
{
string identifier = nextIdMatch.Value;
if (nextIdMatch.Index != inputIndex)
{
// Append everything since the end of the last identifier up to
the start of this identifier
outExpression.Append(expression.Substring(inputIndex,
nextIdMatch.Index - inputIndex));
}
if (variables.Contains(identifier))
{
// Append the variable value
outExpression.AppendFormat("{0}", variables[identifier]);
}
else
{
// Error: no such variable
}
// Move forward and try to match next identifier
inputIndex = nextIdMatch.Index + nextIdMatch.Length;
nextIdMatch = identifierRegex.Match(expression, inputIndex);
}
if (inputIndex < expression.Length)
{
outExpression.Append(expression.Substring(inputIndex));
}
// outExpression will now contain "(45.6 * 100.2) * 20 / 100"
WARNING: This code is untested! I make no guarantees that it will work
exactly as written. It's just to give you an idea.