How to calculate numbers in a C#string

Asked

Viewed 1,084 times

1

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

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

I need to separate only the numbers of this string, sum them together, calculate a simple average over these values stored this average in a variable and show in a textbox show the value.
If anyone can help, I’d appreciate it.

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 on .NET Fiddle

  • 1

    Regex r = new Regex(@"\d+"); Match m = r.Match(str);

  • 1

    Oh no, regex no! : P Creates an answer, is a good alternative.

  • 1

    Yours is faster, outside that would be equal to yours, changing only the 3, 4 line, I will keep as comment, only as alternative, for those who like :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.