Reputation: 402
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
Upvotes: 2
Views: 382
Reputation: 26386
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);
Upvotes: 0
Reputation: 13450
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
Upvotes: 0
Reputation: 4794
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.
Upvotes: 4