"大连" && ("旅游" || "景区") 通过c# 解析这个字符串 并转换成可执行的程序
时间: 2023-09-17 09:07:59 浏览: 30
这个字符串看起来像是一个逻辑表达式,可以通过将其转换为C#代码来实现。以下是一个可能的实现,其中使用了C#中的逻辑运算符和字符串操作函数:
```
string input = "大连 && (旅游 || 景区)";
bool result = false;
// 移除空格
input = input.Replace(" ", "");
// 正则表达式匹配
Match match = Regex.Match(input, @"^\((.*)\)$");
if (match.Success)
{
// 如果字符串以括号包围,则递归调用此函数处理括号内的表达式
input = match.Groups[1].Value;
result = EvaluateExpression(input);
}
else
{
// 解析表达式中的运算符和操作数
string[] parts = input.Split(new string[] { "&&", "||" }, StringSplitOptions.None);
string left = parts[0];
string right = parts[1];
bool leftResult = false;
bool rightResult = false;
// 判断左侧操作数
if (left == "大连")
{
leftResult = true;
}
else if (left.StartsWith("(") && left.EndsWith(")"))
{
// 递归调用此函数处理括号内的表达式
leftResult = EvaluateExpression(left.Substring(1, left.Length - 2));
}
// 判断右侧操作数
if (right == "旅游" || right == "景区")
{
rightResult = true;
}
else if (right.StartsWith("(") && right.EndsWith(")"))
{
// 递归调用此函数处理括号内的表达式
rightResult = EvaluateExpression(right.Substring(1, right.Length - 2));
}
// 根据运算符计算结果
if (input.Contains("&&"))
{
result = leftResult && rightResult;
}
else if (input.Contains("||"))
{
result = leftResult || rightResult;
}
}
// 输出结果
Console.WriteLine(result);
// 递归函数,对表达式进行求值
bool EvaluateExpression(string expression)
{
bool result = false;
// 解析表达式中的运算符和操作数
string[] parts = expression.Split(new string[] { "&&", "||" }, StringSplitOptions.None);
string left = parts[0];
string right = parts[1];
bool leftResult = false;
bool rightResult = false;
// 判断左侧操作数
if (left == "大连")
{
leftResult = true;
}
else if (left.StartsWith("(") && left.EndsWith(")"))
{
// 递归调用此函数处理括号内的表达式
leftResult = EvaluateExpression(left.Substring(1, left.Length - 2));
}
// 判断右侧操作数
if (right == "旅游" || right == "景区")
{
rightResult = true;
}
else if (right.StartsWith("(") && right.EndsWith(")"))
{
// 递归调用此函数处理括号内的表达式
rightResult = EvaluateExpression(right.Substring(1, right.Length - 2));
}
// 根据运算符计算结果
if (expression.Contains("&&"))
{
result = leftResult && rightResult;
}
else if (expression.Contains("||"))
{
result = leftResult || rightResult;
}
return result;
}
```
这个程序会输出 `True`,表明逻辑表达式成立。你可以根据实际需求修改代码。