为逗号分隔字符串函数的解析 [英] Parsing function for comma-delimited string
问题描述
假设我有一个像这样的字符串CMD,参数1,参数2
。该字符串是Arduino的字符串类型。 https://www.arduino.cc/en/Reference/String
Suppose I have a string like this "cmd,param1,param2"
. The String is the Arduino String type. https://www.arduino.cc/en/Reference/String
我要提取每个用逗号分隔的子字符串。我已经成功地写在code像这样的特殊情况。这里的code;
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
}
假设 input_delimited_str =CMD,参数1,参数2,参数3,param4
parserCommaDelimited(input_delimited_str,1)
收益CMD
。 parserCommaDelimited(input_delimited_str,5)
收益param4
。
推荐答案
下面是一个基本的CSV解析器:
The following is a basic CSV parser:
void readCSVline(char *line);
char *readCSVfield(char *line, char *buf);
void readCSVdemo(void)
{
char line[]= "0,,10004,10004,\"Albany Hwy After Galliers Av\",\"\",-32.13649428,116.0176090070,3";
readCSVline(line);
}
/* readCSVline is where you put your "intelligence" about fields to read
* and what to do with them
*/
void readCSVline(char *line)
{
char field1[80], *lineptr=line;
int nfields=0;
while (*lineptr) {
lineptr= readCSVfield(lineptr, field1);
printf("%s\n", field1);
nfields++;
}
printf("%d fields read.\n", nfields);
}
/* readCSVfield reads a field from a CSV line until the next comma or end-of-line.
* It returns where the reading stopped.
*/
char *readCSVfield(char *line, char *buf)
{
int instr= FALSE; // track whether we are in a string
char *cptr= line;
while (*cptr)
{
if (instr) {
if (*cptr=='"') {
char cc= *++cptr;
if (cc=='"') // escaped double quote
*buf++ = '"';
else {
*buf='\0';
cptr--;
instr= FALSE;
}
}
else *buf++ = *cptr;
}
else switch (*cptr) {
case '"': instr= TRUE; break;
case ',': cptr++; *buf= '\0'; return(cptr);
case ' ': case '\t': case '\n': case '\r': break;
default: *buf++ = *cptr;
}
cptr++;
}
*buf= '\0';
return(cptr);
}
这篇关于为逗号分隔字符串函数的解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!