Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 解析中缀表达式,同时将分隔符保留为数组元素_C#_Algorithm_Parsing - Fatal编程技术网

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

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
        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);    
}