Archive

Posts Tagged ‘CSharp’

Convert Infix To Postfix Using C#

August 31st, 2009 Comments off

I remember in mid 2007 I was looking for some CSharp code to convert from infix to postfix. Unfortunately I couldn’t found any readymade code to so. At that time I have written this code. It might be of any help to you. It’s the conversion of algorithm to convert from infix to postfix. If you need any further understanding about this code you are welcome to ask me.

 

private void infixToPostfix(string strExpression)
{
  try

  {
    string strExp = strExpression;
    string
outputExp = string.Empty;
    string
strRevExp = reverseString(strExp);
    string temp = string
.Empty;    while (strRevExp.Length > 0)
    {
      if (strRevExp.IndexOf(” “
) != -1)
        temp = strRevExp.Substring(0, strRevExp.IndexOf(
” “
));
      else

        temp = strRevExp;
      if (!isOperator(temp) && temp != “(“ && temp != “)”)
        outputExp +=
” “
+ temp;
      else if (temp == “)”
)
        sExp.Push(temp);
      else if
(isOperator(temp))
      {
        while (true
)
        {
          if
(sExp.Count == 0)
          {
            sExp.Push(temp);
            break
;
          }
          else if (sExp.Peek() == “)”
)
          {
            sExp.Push(temp);
            break
;
          }
          else if
(isGreaterEqual(temp, sExp.Peek()))
          {
            sExp.Push(temp);
            break
;
          }
          else

            outputExp +=
” “ + sExp.Pop();
        }
      }
      else if (temp == “(“
)
      {
        while (sExp.Peek() != “)”
)
          outputExp +=
” “
+ sExp.Pop();
        sExp.Pop();
      }
      if (strRevExp.IndexOf(” “
) != -1)
        strRevExp = strRevExp.Remove(0, strRevExp.IndexOf(
” “
) + 1);
      else

        strRevExp =
“”;
    }
    while
(sExp.Count != 0)
      outputExp +=
” “
+ sExp.Pop();  catch (Exception ex)
  {
    WriteException(
“infixToPostfix”
, ex);
  }
}

Private string reverseString(string actualString)
{
  string reverseString = string
.Empty;
  try

  {
    string[] strRevExpArray = actualString.Split(‘ ‘);
    for (int
i = strRevExpArray.Length – 1; i >= 0; i–)
      reverseString +=
” “
+ strRevExpArray[i];
    reverseString = reverseString.TrimStart();
  }
  catch (Exception
ex)
  {
    WriteException(
“reverseString”
, ex);
  }
  return
reverseString;
}

Cheers.

Categories: .Net Tags: , , ,