簡體   English   中英

如何從char []字符串中提取數據

[英]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.787001852.4251 (很明顯是,但是怎么樣?)

我是否需要計算逗號,然后在逗號2開始將數字放在一起並停在逗號3並對第二個數字執行相同操作或是否有其他方法? 分裂陣列的方法?

另一個問題就是識別這條線,因為它的開頭是奇怪的字符 - 我如何檢查它們,因為它們不正常並且行為奇怪?

我想要的數據總是以xxxx.xxxxyyyyy.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM