Steven Lemos
Steven Lemos

Reputation: 13

How to add values stores in a string

So i'm currently building a .NC1 file reader for my employer and i'm trying to figure out a quick/efficient way to add the values stores in a string.

Example of the String 'line'

As per the ss above i have a string called line which the following attached to it:

270.00       0.00       0.00       0.00       0.00       0.00       0.00

All i'm asking for it to do is add the 270.00 + 0.00 + 0.00 etc...

What i'm trying to add

Above are the lines in which I will then try to add. (Ignore the first line with v as its default values will always be 0.

Any suggestions?

Upvotes: 0

Views: 91

Answers (2)

bluevulture
bluevulture

Reputation: 412

You can use .Split() on the string, like this:

string[] values = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);

Then just loop through the values array and convert the values to float and add them:

float sum = 0;
foreach (string item in values)
{
  sum += float.Parse(item);
}

Upvotes: 0

Simon Kocurek
Simon Kocurek

Reputation: 2166

Using LINQ:

var result = line.Split(' ', StringSplitOptions.RemoveEmptyEntries)
    .Select(number => decimal.Parse(number))
    .Sum();

Upvotes: 1

Related Questions