How to do calculation with numbers in a String in C #

1

I have a string that Arduino sends to my application through the serial port with the following format:

  

variable = # ultrasound distance # # ultrasound distance # # (with 10 samples equal to this).

I need to separate only the numbers of this string, add them to each other, calculate a simple average on these values stored in this average in a variable and show in a textbox to show the value. If anyone can help, thank you.

    
asked by anonymous 13.01.2016 / 16:45

1 answer

5

Simple.

string str = "#10##10##50##100#";

var listValores = str.Split('#').ToList();
listValores.RemoveAll(x => x == "");

decimal soma = 0;
foreach(var v in listValores)
{
    decimal vlr;
    decimal.TryParse(v, out vlr);

    soma += vlr;
}

decimal media = soma / listValores.Count;

WriteLine($"Soma: {soma} - Média: {media}");

textBox.Text = media;

See working at .NET Fiddle

    
13.01.2016 / 16:49