I have a string input like:
1 3 4 1 2
I want to Sum
the number into integer. I tried the following code:
using System;
public class Program
{
public static void Main()
{
string input2 = "1 3 4 1 1";
string value2 = input2.Replace(" "," ");
int val = int.Parse(value2);
Console.WriteLine(val);
}
}
But it is not correct. Does anyone have an idea for this? Thank you.
CodePudding user response:
You can try Split
the initial string (input2
) into items, TryParse
them into corresponding int
bvalues and then Sum
them with a help of Linq:
using System.Linq;
...
int val = value2
.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Sum(item => int.TryParse(item, out int value) ? value : 0);
Here all invalid items (i.e. items which can't be parsed as an integer) are ignored (we turn them into 0
). You may want an exception thrown in this case:
using System.Linq;
...
int val = value2
.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Sum(item => int.Parse(item));
Finally, your code amended (we can use an old trick with DataTable.Compute
):
using System.Data;
...
string input2 = "1 3 4 1 1";
string formula = input2.Replace(' ', ' ');
using (DataTable table = new DataTable())
{
int val = Convert.ToInt32(table.Compute(formula, null));
Console.WriteLine(val);
}
CodePudding user response:
You can Split input2
with a space character into an array
then use system.linq.enumerable.sum()
string input2 = "1 3 4 1 1";
var result= input2.Split(' ').Sum(x=> int.Parse(x));