正如标题所示,我正在使用以下功能来读取SD卡上某些g代码文件的参数:
long parseParameters(String data, char* c){
int offset = data.indexOf(c);
int offset1 = data.lastIndexOf(" ", offset + 1);
return offset1 > 0 ? data.substring(offset + 1, offset + offset1 + 1).toInt() : data.substring(offset + 1).toInt();
}
void setup(){
Serial.begin(9600);
String q = "P3 S255"; // input
Serial.println(parseParameters(p, "S")); // output
}
void loop(){
}
仅在今天,试图读取字符串P3 S255中的S的值出现在一个小错误中:
INPUT -> OUTPUT
P3 S255 -> 25 (wrong)
A20 P3 S255 -> 255 (Correct)
S255 -> 255 (Correct)
为什么?但是代码对我来说似乎是正确的..我哪里出错了?
提前感谢大家。:)
即是解释:
int offset = data.indexOf(c); //in your example S
"P3 S255";
^
offset = 3
然后解析偏移量1,但在偏移量之后取另一个参数,即“”-但偏移量+1的字符串中没有“”,请参见上方索引所在的位置,因此它返回-1为何?
myString.lastIndexOf(val, from) The index of val within the String, or -1 if not found. But we find something:
offset = 3;
offset1 = 2 ==> offset1 > 0 ==> data.substring(offset + 1, offset + offset1 + 1).toInt()
这导致
data.substring(3 + 1, 3 + 2 + 1).toInt()
"P3 S*4*25*6*5"; which results to 25 as you already know
至(可选):结束子字符串before的索引。
因此,通过更改为],您可以一开始就正确设置S>
data.substring(offset + 1, offset + 1 + offset1 + 1).toInt()
说明:您从偏移量+ 1开始,此偏移量必须与相等(=相同的计算起点)