using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace CStack
{
class example_01
{
static void Main() {
string expression = "5 + 10 + 15 + 20";
Stack nums = new Stack();
Stack ops = new Stack();
Caluate(nums, ops, expression);
Console.WriteLine(nums.Pop());//最终结果
Console.Read();
}
static bool IsNumber(string input) {
bool flag = true;
string pattern = (@"^\d+$");
Regex valodate = new Regex(pattern);//验证 表示不可变的正则表达式
if (!valodate.IsMatch(input))
{
flag = false;
}
return flag;
}
static void Caluate(Stack N,Stack O, string exp) {
string ch, token="";
for (int i = 0; i < exp.Length; i++)
{
ch = exp.Substring(i, 1);
if (IsNumber(ch))
token += ch;//获取数字
if (ch==" "||i==(exp.Length-1))
{
if (IsNumber(token))//是数字
{
N.Push(token);
token = "";
}
}
else if (ch=="+"||ch=="-"||ch=="*" || ch == "/")
O.Push(ch);//操作符号
if (N.Count==2)//满足两个就运算
Compute(N,O);
}
}
/// <summary>
/// 运算
/// </summary>
/// <param name="N"></param>
/// <param name="O"></param>
static void Compute(Stack N, Stack O) {
int oper1, oper2;//俩个操作数字
string oper;//符号
oper1 =Convert.ToInt32( N.Pop());
oper2 = Convert.ToInt32(N.Pop());
oper = Convert.ToString(O.Pop());
switch (oper) {
case "+":
N.Push(oper1+oper2);
break;
case "-":
N.Push(oper1 - oper2);
break;
case "*":
N.Push(oper1 * oper2);
break;
case "/":
N.Push(oper1 /oper2);
break;
default:
break;
}
}
}
}
网友评论