I have implemented class which manages communication with measuring device, which sends list of assignments, like variableName=value
. These assignments are always separated by space. There are two options, the first is simple assignment variableName=value
(without space around equal sign), the second is "array assignment", like variableName[num]= value_1 ... value_num
(here is space after equal sign and between single values).
Here is my code for parser:
/// <summary>
/// Parse variable value "y" from assignment pair "x=y"
/// </summary>
/// <param name="s">string where "x=y" pairs are separated by space</param>
/// <param name="varName">left side of assignment</param>
/// <returns>right side of assignment</returns>
private static string ParseEqualValue(string s, string varName)
{
int startPos = s.IndexOf("=", s.IndexOf(varName)) + 1;
int endPos = s.IndexOf(" ", startPos);
return s.Substring(startPos, endPos - startPos);
}
/// <summary>
/// Parse variable values after "=" from string
/// </summary>
/// <param name="s">string in format: varName[num]= x1 .. xnum</param>
/// <param name="varName">left side of assignment</param>
/// <returns>right side of assignment in the list</returns>
private static List<string> ParseEqualValues(string s, string varName)
{
List<string> list = new List<string>();
// position of ShapeX..
int varPos = s.IndexOf(varName);
// parsing of numPts value in []
int numStartPos = s.IndexOf("[", varPos) + 1;
int numEndPos = s.IndexOf("]", numStartPos);
int num = 0;
int.TryParse(s.Substring(numStartPos, numEndPos - numStartPos), out num);
int startPos = s.IndexOf("=", varPos) + 2;
for (int i = 0; i < num; i++)
{
int endPos = s.IndexOf(" ", startPos);
if (endPos < 0)
endPos = s.Length;
list.Add(s.Substring(startPos, endPos - startPos));
startPos = endPos + 1;
}
return list;
}
And here how I use it:
/// <summary>
/// Create ColdTest cut from ProfRoll answer
/// </summary>
/// <param name="s">Answer from ProfRoll</param>
/// <returns></returns>
public static Cut CreateColdTestCut(string s)
{
Cut cut = new Cut();
cut.pts = new List<PointF>();
int numShapes;
double.TryParse(ParseEqualValue(s, "AvgTemp"), out cut.pyroTemp);
double.TryParse(ParseEqualValue(s, "MinTemp"), out cut.tempMin);
double.TryParse(ParseEqualValue(s, "MaxTemp"), out cut.tempMax);
int.TryParse(ParseEqualValue(s, "NumShapes"), out numShapes);
List<int> numPts = new List<int>();
for (int i = 0; i < numShapes; i++)
{
List<string> xPts = ParseEqualValues(s, string.Format("ShapeX{{0}}", i));
List<string> yPts = ParseEqualValues(s, string.Format("ShapeY{{0}}", i));
if (xPts.Count != yPts.Count)
break;
numPts.Add(xPts.Count);
for (int j = 0; j < xPts.Count; j++)
{
try
{
cut.pts.Add(new PointF(float.Parse(xPts[j]), float.Parse(yPts[j])));
}
catch { }
}
}
cut.isColdTest = true;
cut.time = DateTime.Now;
cut.numCurves = cut.numPts.Length;
return cut;
}
I will be glad for any critical comments.