我有如下输入:
"10+18+12+13"
"10+18-12+13"
"2-5"
例如数字后跟一个"+"
或"-"
我创建的类MathOper
public class MathOper
{
public int Num { get; set; }
public string Oper { get; set; } //this display the number will be operated.
}
"10+18-12+13"
我想返回MathOper 列表,如下所示
new MathOper(){Num=10,"+"}
new MathOper(){Num=18,"+"}
new MathOper(){Num=12,"-"}
new MathOper(){Num=13,"+"}
我试图通过这种方式编码:
public class MathOperCreator
{
private readonly string _mathString;//8+2-3
public MathOperCreator(string mathString)
{
this._mathString = mathString.Trim();
}
public List<MathOper> Create()
{
var lMo = new List<MathOper>();
int l = this._mathString.Length;//5
for (int i = 0; i < l; i = i + 2)
{
char n = _mathString[i];
int n1 = int.Parse(n.ToString(CultureInfo.InvariantCulture));
string o1 = "+";
if (i > 0)
{
o1 = _mathString[i - 1].ToString(CultureInfo.InvariantCulture);
}
var mo = new MathOper { Num = n1, Oper = o1 };
lMo.Add(mo);
}
return lMo;
}
}
我发现它只适用于带有一个字符的数字,如果数字是两个字符,例如 18 ,它就不起作用。请建议如何实现描述的功能?