Suppose I have a string like this "cmd,param1,param2"
. The String is the Arduino String type. https://www.arduino.cc/en/Reference/String
I want to extract each of the substrings separated by commas. I have successfully written the code for a specific case like this. Here's the code;
String = str_data('cmd,param1,param2');
int firstCommaIndex = str_data.indexOf(',');
int secondCommaIndex = str_data.indexOf(',', firstCommaIndex+1);
String cmd = str_data.substring(0, firstCommaIndex);
String param1 = str_data.substring(firstCommaIndex+1, secondCommaIndex);
String param2 = str_data.substring(secondCommaIndex+1);
My problem is to have a function that solves the general case. The string can be delimited with any number of commas. I would like to have a function that looks like this;
String parserCommaDelimited(String input_delimited_str, int nth_param_num)
{
//implementation
}
Suppose input_delimited_str="cmd,param1,param2,param3,param4"
parserCommaDelimited(input_delimited_str, 1)
returns "cmd"
.
parserCommaDelimited(input_delimited_str, 5)
returns "param4"
.
The following is a basic CSV parser:
You can split string as below and get whatever you want.
try with split, in c++ is strtok:
variable = strtok(variable,"delimiter"); converts the string into array, in c++ i don't know, I'm programming with php & javascript, but you can watch it on:
http://www.cplusplus.com/reference/cstring/strtok/
I hope it helps you!