0

I have a string that is "1+1". When I do a int.Parse on it, "11" is outputted. Is there any way to make it find the sum?

Code: (settings is IsolatedStorageSettings, which is the 1+1 string)

MessageBox.Show(int.Parse(settings["favoritesnum"].ToString()).ToString());
Kevin
  • 383
  • 2
  • 11
  • No, that's an example. Doesn't really make a difference as it is always an addition problem. – Kevin Jan 12 '15 at 03:14
  • Not all answers may apply for Windows Phone, but here are some suggestions how to do this in C#: http://stackoverflow.com/questions/174664/operators-as-strings – Thilo Jan 12 '15 at 03:16
  • @Kevin. Yes, it makes a difference. Is it always exactly two summands? Can there be negative numbers? Can there be whitespace? – Thilo Jan 12 '15 at 03:18
  • No whitespace, any number of summands possible. Also no - numbers. Why are all of the awnsers in that question so complex? It's just a math problem. – Kevin Jan 12 '15 at 03:19

1 Answers1

5

Given what you stated in the comments, that it's always addition (and assuming the input is guaranteed to be valid, and not "1+2+B"), you could split on the + sign and sum up the individual numbers:

string expr = "1+1";

int sum = expr.Split('+').Sum(i => int.Parse(i));  // 2
Grant Winney
  • 65,241
  • 13
  • 115
  • 165