我正在制作一个控制3D打印机的小程序。当我发送一些东西时,它通常会以响应ok
,但是如果出现问题,它会发送如下信息:
T:221.0 /220.0 @:0 W:1
如果它有适当的定界符,我可以轻松地对其进行解析,但是由于有string,因此使用空间并不可靠221.0 /220.0
。因此,如果我将空格用作定界符,则/220.0
可以将其视为键值对,但是由于键位于under,因此没有键T
。我打算获取每个冒号的索引,并在其后面简单地以1个字符开头,但是密钥长度也是可变的。例如:
T:221.0 /220.0 B@:127 @:0 W:1
B@
现在有两个字符长。
我进行了一些研究,但发现的所有内容都有适当的分隔符,例如带有数据的URL。
http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.cld&datum=201311161500&cultuur=en-GB&continent=europa
我打算获取每个冒号的索引,然后在找到冒号作为起点时向后搜索一个空间。同样,下一个键值对的起点将用作上一个键值对的终点。但是,我不确定这是否是正确的方法。
主要问题: 如何解析没有适当定界符的字符串?我真的没有特定的要求。可以是数组或列表,可以将键和值的变量分开,也可以将所有内容推入数组,以便
string[] data = {key1,value1,key2,value2,key3,value3};
更新:这是第二个示例中的键/值对:
Key:Value
T:221.0 /220.0
B@:127
@:0
W:1
一些示例:
T:221.0 /220.0 B:85.7 /120 B@:30W @:0 W:8
Key:Value
T:221.0 /220.0
B:85.7 /120
B@:30W
@:0
W:8
这是另一个更复杂的例子:
T:171.4 /220.0 B:90.3 /120 T1:171.4 /220.0 B@:30 @:12W W:6
Key:Value
T:171.4 /220.0 // Temperature of first nozzle heater
B:90.3 /120 // Temperature of the hot plate it's printing on
T1:171.4 /220.0 // Temperature of the second nozzle heater if it exists
B@:30 // Raw power consumption of hotbed (unit depends on config)
@:12W // Power of of nozzle in Watts (unit depends on config)
W:6 // Waiting time (in seconds). If the optimal conditions are met and this counts down to zero, printing resumes. Else, reset to 10.
样本字符串开头的空格是有意的。它确实以空格开头。对于那些感兴趣的人,这些是运行Marlin 3D打印固件的Arduino Mega的答复。这些是打印机加热器温度尚未高到无法挤出时的答复。
我会遵循以下逻辑:
代码:
private List<KeyValuePair<string, string>> ParsePrinterResponse(string rawResponse)
{
List<KeyValuePair<string, string>> pairs = new List<KeyValuePair<string, string>>();
string[] colonItems = rawResponse.Trim().Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
if (colonItems.Length > 1)
{
string currentKey = colonItems[0], currentValue = "";
for (int i = 1; i < colonItems.Length; i++)
{
string currentItem = colonItems[i];
int spaceIndex = currentItem.LastIndexOf(" ");
if (spaceIndex < 0)
{
//end of string, whole item is the value
currentValue = currentItem;
}
else
{
//middle of string, left part is value, right part is next key
currentValue = currentItem.Substring(0, spaceIndex);
}
pairs.Add(new KeyValuePair<string, string>(currentKey, currentValue));
currentKey = currentItem.Substring(spaceIndex + 1);
}
}
return pairs;
}
用法样本:
errorBox.Lines = ParsePrinterResponse("T:171.4 /220.0 B:90.3 /120 T1:171.4 /220.0 B@:30 @:12W W:6").ConvertAll(p =>
{
return string.Format("{0}:{1}", p.Key, p.Value);
}).ToArray();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句