我正在使用Arduino並從串行接收字符串。我已將該字符串轉換爲字符數組。但我需要將該數組的前4個或5個元素轉換回字符串。有沒有辦法做到這一點?如何將可變數量的char數組元素轉換爲字符串
我嘗試以下,但它不工作:
String str= String('a[0]');
我正在使用Arduino並從串行接收字符串。我已將該字符串轉換爲字符數組。但我需要將該數組的前4個或5個元素轉換回字符串。有沒有辦法做到這一點?如何將可變數量的char數組元素轉換爲字符串
我嘗試以下,但它不工作:
String str= String('a[0]');
你想要的是一個std::string
的substr
方法。
您可以convetr the char[]
to an std::string
,然後使用substr
獲取所需的子字符串。
std::string str("The quick brown fox jumps over the lazy dog");
std::cout << str.substr(0, 9);
輸出將是:
快速
char arr[m];
std::string str="";
for(int i = 0; i < n; i++) {
str += arr[i];
}
我假設你想前n個元素轉換的char aar
成字符串。
或者
char* inp = ..;
int size = 4; // int size = 5;
std::string str(inp, size);
你沒有檢查邊界。如果'n> m'? –
另外,'std :: string'有一個構造函數。 –
@IvanRubinson:正如OP提到的那樣,他/她想要將前4或5個字符轉換爲字符串。因此,我認爲,'m> n'。 – Shravan40
char* data = ...;
int size = 4;
std::string str(data, size);
它的優雅與的std :: string的構造函數。
感謝您對ivan的快速響應。我試圖在這裏做什麼是從串行獲取字符串。如果字符串以COMSTEP開頭,則進入函數,在該函數中分析字符串的其餘部分並標記它。字符串由空格分隔的字符組成。我必須將字符串轉換爲字符還是有任何其他方式來做到這一點? P.S:我是arduino的noob。所以任何幫助讚賞 –
如果你已經有一個字符串,沒有必要轉換它。只需將你有的字符串子串。 –