试图妥善字符串
问题描述:
考虑下面的函数串0 0 0
试图妥善字符串
虽然它对R:255,G:0,B:0,
或R:0,G:255,B:0,
正常工作。
int setColor(String command) {
//Parse the incoming command string
//Example command R:123,G:100,B:50,
//RGB values should be between 0 to 255
int red = getColorValue(command, "R:", "G");
int grn = getColorValue(command, "G:", "B");
int blu = getColorValue(command, "B:", ",");
// Set the color of the entire Neopixel ring.
uint16_t i;
for (i = 0; i < strip.numPixels(); i++) {
strip.setPixelColor(i, strip.Color(red, grn, blu));
}
strip.show();
return 1;
}
int getColorValue(String command, String first, String second) {
int rgbValue;
String val = command.substring(command.indexOf(first)+2, command.indexOf(second));
val.trim();
rgbValue = val.toInt();
return rgbValue;
}
答
我可以假设command.indexOf(second)
总能找到你的第一逗号,因此对于B
的val
变空字符串。
假设indexOf
类似于.Net's的东西,也许尝试
int start = command.indexOf(first)+2;
int end = command.indexOf(second, start)
String val = command.substring(start+2, end);
注意第二个呼叫indexOf
第二个参数,我想这会让indexOf
寻找匹配start
后。我也认为你最好通过一个","
作为second
为所有呼叫,并且添加+1或-1到end
以补偿这个通过","
而不是"G"
和"B"
。
或仅为B
部分使用另一个限制器,如R:0,G:0,B:0.
(点而不是逗号)。
答
不知道你的String
实现,我只能让一个受过教育的猜测。 会发生什么,indexOf(second)
不会给你你的想法。
"R:0,G:0,B:255,"
^ ^- indexOf("B:")
|- indexOf(",")
它适用于您的其他情况,因为它们查找的内容都不会在字符串中多次出现。
看看SparkCore Docs我们找到indexOf
和substring
的文档。
indexOf() 在另一个字符串中查找字符或字符串。默认情况下,从字符串的开始处开始搜索,但也可以从给定索引处开始搜索,以便查找字符或字符串的所有实例。
string.indexOf(val)
string.indexOf(val, from)
子()
string.substring(from)
string.substring(from, to)
所以现在解决您的问题,您可以使用的indexOf
第二方案,并通过该指数你在第一次搜索中找到。
int getColorValue(String command, String first, String second) {
int rgbValue;
int beg = command.indexOf(first)+2;
int end = command.indexOf(second, beg);
String val = command.substring(beg, end);
val.trim();
rgbValue = val.toInt();
return rgbValue;
}
答
最后我只是修改我的代码:
int setColor(String command) {
int commaIndex = command.indexOf(',');
int secondCommaIndex = command.indexOf(',', commaIndex+1);
int lastCommaIndex = command.lastIndexOf(',');
String red = command.substring(0, commaIndex);
String grn = command.substring(commaIndex+1, secondCommaIndex);
String blu = command.substring(lastCommaIndex+1);
// Set the color of the entire Neopixel ring.
uint16_t i;
for (i = 0; i < strip.numPixels(); i++) {
strip.setPixelColor(i, strip.Color(red.toInt(), grn.toInt(), blu.toInt()));
}
strip.show();
return 1;
}
我干脆只是做:255,0,0
和它的工作原理治疗。
答
在这个例子中,我将使用逗号分隔字符串作为分隔符,然后将每个子字符串解析为键值对。如果你总是有序列“R,G,B”,在这种情况下为什么要有“R:”,“G:”或“B:”,你可以为第二部分使用一个向量值?
你正在使用什么'String'实现? – developerbmw
我们需要知道你正在使用的'String'类是如何工作来评估问题的。否则,我们只能猜测。是否有任何特定的原因,您没有使用C++标准库字符串实现? ('std :: string') – developerbmw
你应该通过引用传递所有字符串,或者更好的是,作为const引用。 – Lundin