简体   繁体   English

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

[英]How to extract data from a char[] string

Currently I have a GPS connected to my Arduino chip which outputs a few lines every second. 目前我的GPS连接到我的Arduino芯片,每秒输出几行。 I want to extract specific info from certain lines. 我想从某些行中提取特定信息。

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

(Take note of the characters) (记下字符)

If I read this line into a char[] , is it possible to extract 3355.7870 and 01852.4251 from it? 如果我将这一行读入char[] ,是否可以从中提取3355.787001852.4251 (Well obviously it is, but how?) (很明显是,但是怎么样?)

Would I need to count the commas and then after comma 2 start putting the number together and stop at comma 3 and do the same for second number or is there another way? 我是否需要计算逗号,然后在逗号2开始将数字放在一起并停在逗号3并对第二个数字执行相同操作或是否有其他方法? A way to split up the array? 分裂阵列的方法?

The other problem with this is identifying this line because of the strange characters at it's beginning - how do I check them, because their not normal and behaves strangely? 另一个问题就是识别这条线,因为它的开头是奇怪的字符 - 我如何检查它们,因为它们不正常并且行为奇怪?

The data I want is always in form xxxx.xxxx and yyyyy.yyyy and are unique in that form, meaning I could maybe search trough all the data not caring about which line it's on and extract that data. 我想要的数据总是以xxxx.xxxxyyyyy.yyyy形式存在,并且在该形式中是唯一的,这意味着我可以搜索所有数据,而不是关注它所在的数据并提取该数据。 Almost like a preg-match, but I have no idea how to do that with a char[] . 几乎像一个preg-match,但我不知道如何使用char[]

Any tips or ideas? 任何提示或想法?

You can tokenize (split) the string on the comma using strtok , and then parse the numbers using sscanf . 您可以使用strtok对逗号上的字符串进行标记(拆分),然后使用sscanf解析数字。

Edit: C example: 编辑: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);
}

If you have strange characters at the beginning of the string, then you should start parsing it from the end: 如果你在字符串的开头有奇怪的字符,那么你应该从头开始解析它:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM