evaluate boolean string?

C

Coco

Hi!
Does c# has any class method that will be able to evaluate
a given string e.g ((True && False) || (True && True)) and
return the result in boolean for this case is true

Thanks!
 
G

Girish Bharadwaj

Coco said:
Hi!
Does c# has any class method that will be able to evaluate
a given string e.g ((True && False) || (True && True)) and
return the result in boolean for this case is true

Thanks!

No. But, you can implement a very simple "interpreter" pattern with C#
and get the behavior. Search web for Dotnet and patterns.. you might see
someone already implemented this stuff.
 
C

Coco

Thankf for the help, but i am not sure so sure how can it
be done, can u tell me more?
 
B

Bret Mulvey [MS]

Coco said:
Hi!
Does c# has any class method that will be able to evaluate
a given string e.g ((True && False) || (True && True)) and
return the result in boolean for this case is true

Thanks!

Here's a simple class that can do it. It's not very efficient--for better
speed and memory use you'd want to use something else. Look up "infix
evaluation" for some more ideas. But this one is short and sweet and it's
fun to watch the expression cave in on itself each time through the loop.
You can easily extend it to include ==, != and other operators.

class BooleanEvaluator
{
public static bool Evaluate(string expression)
{
expression =
expression.ToLower(System.Globalization.CultureInfo.InvariantCulture);
expression = expression.Replace("false", "0");
expression = expression.Replace("true", "1");
expression = expression.Replace(" ", "");
string temp;
do
{
temp = expression;
expression = expression.Replace("(0)", "0");
expression = expression.Replace("(1)", "1");
expression = expression.Replace("0&&0", "0");
expression = expression.Replace("0&&1", "0");
expression = expression.Replace("1&&0", "0");
expression = expression.Replace("1&&1", "1");
expression = expression.Replace("0||0", "0");
expression = expression.Replace("0||1", "1");
expression = expression.Replace("1||0", "1");
expression = expression.Replace("1||1", "1");
}
while (temp != expression);
if (expression == "0")
return false;
if (expression == "1")
return true;
throw new ArgumentException("expression");
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top