C# 解析中缀表达式,同时将分隔符保留为数组元素
C#是否有一种方法可以让我解析如下内容:C# 解析中缀表达式,同时将分隔符保留为数组元素,c#,algorithm,parsing,C#,Algorithm,Parsing,C#是否有一种方法可以让我解析如下内容: "(h1+h2+h3)" into a string array {"(", "h1", "+", "h2", +, "h3", + ")"} ? 我正在实施调车场算法,我不想因为没有代币而找麻烦 编辑:我刚刚写了我自己的解决方案 private string[] parseExp(string exp) { // it will be at least as long as the input string st
"(h1+h2+h3)" into a string array {"(", "h1", "+", "h2", +, "h3", + ")"} ?
我正在实施调车场算法,我不想因为没有代币而找麻烦
编辑:我刚刚写了我自己的解决方案
private string[] parseExp(string exp)
{
// it will be at least as long as the input string
string[] parsed = new string[exp.Length];
int index = 0;
foreach(char c in exp)
{
if(op.Contains(c))
{
index++;
parsed[index++] += c.ToString();
}else
{
parsed[index] += c.ToString();
}
}
Array.Resize(ref parsed, index + 1);
return parsed;
}
您可以尝试重新排列表达式,以便使用String.split操作拆分它,但在这种情况下,您需要知道表达式可能具有的所有符号
string input="(h1+h2+h3)";
String newString = input.Replace("("," ( ").Replace(")"," )
"
).Replace("+"," + "); // Reformat string by separating symbols
String[] splitStr = newString.Split(new char[]{' '});
foreach(string x in splitStr)
{
Console.WriteLine(x);
}
您可以尝试重新排列表达式,以便使用String.split操作拆分它,但在这种情况下,您需要知道表达式可能具有的所有符号
string input="(h1+h2+h3)";
String newString = input.Replace("("," ( ").Replace(")"," )
"
).Replace("+"," + "); // Reformat string by separating symbols
String[] splitStr = newString.Split(new char[]{' '});
foreach(string x in splitStr)
{
Console.WriteLine(x);
}