Anonymous - 2 years ago
879 0

Input a string like this one: 2+4*3+2-6/2

C#

# basic string calculator

``````public static double calc(string str)  // solves math strings with +, -, /, and * only
{
string[] b1 = Regex.Split(str, @"([+-])").Select(p => p.Trim()).ToArray();           // break by + -
for (int i = 0; i < b1.Length; i++)
{
string[] b2 = Regex.Split(b1[i], @"([*/])").Select(p => p.Trim()).ToArray();           // break by * /
while (b2.Length>2)
{
// multiplication and division gets calculated first
if (b2[1] == "*") b2[2] = Convert.ToString(Convert.ToDouble(b2[0]) * Convert.ToDouble(b2[2]));
if (b2[1] == "/") b2[2] = Convert.ToString(Convert.ToDouble(b2[0]) / Convert.ToDouble(b2[2]));
b2= b2.Skip(2).ToArray();
}
b1[i] = b2[0];
}
while (b1.Length > 2)
{
// addition and subtraction gets calculated last
if (b1[1] == "+") b1[2] = Convert.ToString(Convert.ToDouble(b1[0]) + Convert.ToDouble(b1[2]));
if (b1[1] == "-") b1[2] = Convert.ToString(Convert.ToDouble(b1[0]) - Convert.ToDouble(b1[2]));
b1 = b1.Skip(2).ToArray();
}
return Convert.ToDouble(b1[0]);
}``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download