[英]How to extract data from a char[] string
目前我的GPS连接到我的Arduino芯片,每秒输出几行。 我想从某些行中提取特定信息。
$ÇÐÇÇÁ,175341.458,3355.7870,O,01852.4251,A,1,03,5.5,-32.8,I,32.8,我,, 0000 * 57
(记下字符)
如果我将这一行读入char[]
,是否可以从中提取3355.7870
和01852.4251
? (很明显是,但是怎么样?)
我是否需要计算逗号,然后在逗号2开始将数字放在一起并停在逗号3并对第二个数字执行相同操作或是否有其他方法? 分裂阵列的方法?
另一个问题就是识别这条线,因为它的开头是奇怪的字符 - 我如何检查它们,因为它们不正常并且行为奇怪?
我想要的数据总是以xxxx.xxxx
和yyyyy.yyyy
形式存在,并且在该形式中是唯一的,这意味着我可以搜索所有数据,而不是关注它所在的数据并提取该数据。 几乎像一个preg-match,但我不知道如何使用char[]
。
任何提示或想法?
您可以使用strtok对逗号上的字符串进行标记(拆分),然后使用sscanf解析数字。
编辑:C示例:
void main() {
char * input = "$ÇÐÇÇÁ,175341.458,3355.7870,Ó,01852.4251,Å,1,03,5.5,-32.8,Í,32.8,Í,,0000*57";
char * garbage = strtok(input, ",");
char * firstNumber = strtok(NULL, ",");
char * secondNumber = strtok(NULL, ",");
double firstDouble;
sscanf(firstNumber, "%lf", &firstDouble);
printf("%f\n", firstDouble);
}
如果你在字符串的开头有奇怪的字符,那么你应该从头开始解析它:
char* input = get_input_from_gps();
// lets assume you dont need any error checking
int comma_pos = input.strrchr(',');
char* token_to_the_right = input + comma_pos;
input[comma_pos] = '\0';
// next strrchr will check from the end of the part to the left of extracted token
// next token will be delimited by \0, so you can safely run sscanf on it
// to extract actual number
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.