如何从char[]字符串中提取数据

3

目前我已经将GPS连接到我的Arduino芯片上,每秒输出几行数据。 我想从某些行中提取特定的信息。

$ÇÐÇÇÁ,175341.458,3355.7870,Ó,01852.4251,Å,1,03,5.5,-32.8,Í,32.8,Í,,0000*57

(请注意字符)

如果我将此行读入char[]中,是否可以从中提取3355.787001852.4251? (很明显,可以,但是如何操作呢?)

我需要计算逗号的数量,然后在第二个逗号之后开始组合数字,并在第三个逗号停止,然后对第二个数字执行相同的操作吗? 还是有其他方法? 有一种方法可以拆分数组吗?

这种方法的另一个问题是如何识别这一行,因为它的开头有奇怪的字符-如何检查它们,因为它们不是正常的并且行为怪异?

我要提取的数据始终以xxxx.xxxxyyyyy.yyyy的形式存在,并且在该形式中是唯一的,这意味着我可以搜索所有数据而不关心它位于哪一行并提取该数据。 就像preg-match一样,但我不知道如何使用char []进行操作。

有任何提示或想法吗?

2个回答

2
您可以使用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);
}

注意:strtok 会直接修改原字符串。 - BoBTFish
1
那将是 char input[] = ...;。你的代码试图修改一个字符串常量,这会导致未定义的行为。(当然,在真实的代码中这不是问题)。 - Mike Seymour

0
如果您在字符串开头有奇怪的字符,那么您应该从末尾开始解析它:
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接