2015-04-23 91 views
1

考慮下面的函數串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; 
} 
+1

你正在使用什麼'String'實現? – developerbmw

+0

我們需要知道你正在使用的'String'類是如何工作來評估問題的。否則,我們只能猜測。是否有任何特定的原因,您沒有使用C++標準庫字符串實現? ('std :: string') – developerbmw

+0

你應該通過引用傳遞所有字符串,或者更好的是,作爲const引用。 – Lundin

回答

0

我可以假設command.indexOf(second)總能找到你的第一逗號,因此對於Bval變空字符串。

假設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.(點而不是逗號)。

2

不知道你的String實現,我只能讓一個受過教育的猜測。 會發生什麼,indexOf(second)不會給你你的想法。

"R:0,G:0,B:255," 
    ^ ^- indexOf("B:") 
    |- indexOf(",") 

它適用於您的其他情況,因爲它們查找的內容都不會在字符串中多次出現。

看看SparkCore Docs我們找到indexOfsubstring的文檔。

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; 
} 
0

最後我只是修改我的代碼:

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和它的工作原理治療。

1

在這個例子中,我將使用逗號分隔字符串作爲分隔符,然後將每個子字符串解析爲鍵值對。如果你總是有序列「R,G,B」,在這種情況下爲什麼要有「R:」,「G:」或「B:」,你可以爲第二部分使用一個向量值?