C#是否有办法解析这样的事情:
"(h1+h2+h3)" into a string array {"(", "h1", "+", "h2", +, "h3", + ")"} ?
我正在实施 Shunting-yard算法,我不想为没有令牌而努力。
编辑:我刚刚编写了自己的解决方案
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;
}
答案 0 :(得分:0)
您可以尝试重新排列表达式,以便可以使用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);
}