2

I am trying to parse data I am getting from an arduino robot I created. I currently have my serial program up and running and I am able to monitor the data being sent and received by my computer.

The data I am trying to get from the robot includes: speed, range, and heading. The data being sent from the arduino are floats.

I use a single character to denote what the data being received is by either a S,R, or H. For example: R150.6

This would denote that this is range data and 150.6 would be the new range to update the program with.

I'm a little stuck trying to figure out the best way to parse this using c# as this is my first c# program.

I have tried with a similar code to:

if (RxString[0] == 'R')
            Range = double.Parse(RxString);

I read on the site to use regular expressions, however I am having a hard time figuring out how to incorporate it into my code.

This is the link I was using for guidance:

String parsing, extracting numbers and letters

Community
  • 1
  • 1
pr-
  • 402
  • 2
  • 9
  • 18
  • Your example is calling double.Parse("R150.6"). You would want, at minimum, to remove the first digit before trying to parse the number. – Wug Jul 03 '12 at 18:15

3 Answers3

4

You're almost there. If you're always starting with a single letter, try Range = double.Parse(RxString.Substring(1)). It will read from the second character on.

Kevin Aenmey
  • 13,259
  • 5
  • 46
  • 45
Arithmomaniac
  • 4,604
  • 3
  • 38
  • 58
  • I entered it as you stated, however I find that my numbers are getting split at the decimal. So one line says: 147 and the next one shows a 0. I don't know if that is related to my Parse or the fact that I am using a command to convert from double to a string. This is the command I am using: textBox1.AppendText(Range.ToString()); – pr- Jul 03 '12 at 18:31
0

i can use regex for find double:

\d+([,\.]\d+)?

using:

Regex re = Regex.Match("R1.23", "\d+([,\.]\d+)?");
if (re.Success)
{
     double @double = Convert.ToDouble(re.Value, System.Globalization.CultureInfo.InvariantCulture);
}

it garanties to get first decimal from string if your letter migrate in string or adding other symbols

burning_LEGION
  • 13,246
  • 8
  • 40
  • 52
  • 1
    This would work just fine however in this case a Regular Expression is a pretty expensive way to remove a character from a string. – ian.shaun.thomas Jul 03 '12 at 18:25
0

Since you know the format of the returned data, you can try something like this

data = RxString.SubString(0,1);
value = RxString.SubString(1, RxString.Length-1);

if(data == "R")
  range = double.Parse(value);
codingbiz
  • 26,179
  • 8
  • 59
  • 96