问题
(Calculator program)count in one step with math basic order
if there is a string = "5+2*6/9"(which is user input) how to get number 2 and 6? i've been trying with split but if there is no '+' it fail :(
here is my code atm
string[] a = kalimat.Split('*');
string[] a1 = a[0].Split('+');
string[] a2 = a1[a1.Count() - 1].Split('-');
string[] b1 = a[1].Split('+');
string[] b2 = b1[0].Split('-');
ang1 = a2[a2.Count() - 1];
ang2 = b2[0];
angka1 = Convert.ToDouble(ang1);
angka2 = Convert.ToDouble(ang2);
hasil = angka1 * angka2;
any idea guys?
回答1:
If you're input expression is always in the form: "[some number]+[first value you want to return]*[second value you want to return]" then this should work for you:
var reg = new System.Text.RegularExpressions.Regex(@"\d\+(\d)\*(\d)");
var result = reg.Match("5+2*6/9");
var first = result.Groups[1];
var second = result.Groups[2];
You can of course tweak the regular expression search pattern to suit your needs.
回答2:
Parsing arbitrary mathematical expression is not a trivial task. If this isn't a homework that require you to do the parsing by hand, I would suggest to find a library for doing the task, like NCalc for example.
You can install it from Nuget, and use the following simple code :
var kalimat = "5+2*6/9";
var hasil = new NCalc.Expression(kalimat).Evaluate();
Console.WriteLine(hasil);
Selamat mencoba :)
来源:https://stackoverflow.com/questions/29578062/split-string-c-sharp-based-on-math-operator