您的位置:首页 > 其它

解析 简单的字符串计算公式

2013-01-28 17:28 369 查看
只是简单的 加减乘除
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
public  class StrCount
{
public static string StrToCount(string stw)
{
string st = GetNewstring(stw);
string[] strA = st.Split('|');
for (int i = 0; i < strA.Length; i++)
{
if (strA[i] == "*" || strA[i] == "/")
{
strA[i + 1] = CountStr(strA[i - 1], strA[i + 1], strA[i]);
strA[i - 1] = "";
strA[i] = "";
}
}
string[] strA1 = GetNewstring(ArtoString(strA)).Split('|');
for (int i = 0; i < strA1.Length; i++)
{
if (strA1[i] == "+" || strA1[i] == "-")
{
strA1[i + 1] = CountStr(strA1[i - 1], strA1[i + 1], strA1[i]);
strA1[i - 1] = "";
strA1[i] = "";
}
}
return ArtoString(strA1);
}

/// <summary>
/// 计算字符串
/// </summary>
/// <param name="number1"></param>
/// <param name="number2"></param>
/// <param name="stype"></param>
/// <returns></returns>
static string CountStr(string number1, string number2, string stype)
{
decimal d1 = Convert.ToDecimal(number1);
decimal d2 = Convert.ToDecimal(number2);
string sre = "";
switch (stype)
{
case "*":
sre = (d1 * d2).ToString();
break;
case "/":
sre = (d1 / d2).ToString();
break;
case "+":
sre = (d1 + d2).ToString();
break;
case "-":
sre = (d1 - d2).ToString();
break;
}
return sre;
}

/// <summary>
/// 数组转成字符串
/// </summary>
/// <param name="sA"></param>
/// <returns></returns>
static string ArtoString(string[] sA)
{
string strresult = "";
foreach (string item in sA)
{
if (item.Trim() != "")
{
strresult += item;
}
}
return strresult;
}
/// <summary>
/// 向字符串中插入“|”并返回新的字符串;
/// </summary>
/// <param name="st"></param>
/// <returns></returns>
static string GetNewstring(string st)
{
//添加"|"以便于分组
if (st.IndexOf('+') != -1)
{
st = st.Replace("+", "|+|");
}
if (st.IndexOf('-') != -1)
{
st = st.Replace("-", "|-|");
}
if (st.IndexOf('*') != -1)
{
st = st.Replace("*", "|*|");
}
if (st.IndexOf('/') != -1)
{
st = st.Replace("/", "|/|");
}
return st;
}
}
}
如果有误,敬请指正。。谢谢。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: