0

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?

Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • 1
    Is there anything you've tried so far? – Cid May 05 '21 at 09:44
  • Welcome to StackOverflow! Please read [ask]. In particular, please make sure that your question includes everything we need to know as text -- don't post images of text. This makes your question easier to read, and means people are more likely to answer it. You also need to attempt to solve it yourself, and show the code you've tried, so please [edit] that into your question as well. Your problem involves a number of tasks (splitting the string, parsing the bits as numbers, adding them, etc): attempt them one-by-one, and if you have specific problems, ask – canton7 May 05 '21 at 09:44
  • 2
    Posing a question which may highlight your lack of detail: whats wrong with `line += datatobeadded` – Nick.Mc May 05 '21 at 09:44
  • Use a Replace in the line ? – Philippe May 05 '21 at 09:46

2 Answers2

1

Using LINQ:

var result = line.Split(' ', StringSplitOptions.RemoveEmptyEntries)
    .Select(number => decimal.Parse(number))
    .Sum();
Šimon Kocúrek
  • 1,591
  • 1
  • 12
  • 22
0

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);
}
bluevulture
  • 422
  • 4
  • 16