从C中使用“sscanf”函数的字符串解析子字符串

时间:2016-02-05 15:51:09

标签: c arrays string parsing substring

我有一个像下面这样的gps字符串:

char gps_string[] = "$GPRMC,080117.000,A,4055.1708,N,02918.9336,E,0.00,316.26,00,,,A*78";

我想解析逗号之间的子串,如下面的序列:

$GPRMC
080117.000
A
4055.1708
.
.
.

我尝试过sscanf功能,如下所示:

 sscanf(gps_string,"%s,%s,%s,%s,%s,",char1,char2,char3,char4,char5);

但这不起作用。如果在函数上面使用,则char1数组获取整个字符串。

实际上我在之前的算法中使用了strchr函数并且使它工作但是如果我可以使用sscanf并且在子字符串中获取这些参数它会更容易和更简单。

顺便说一句,逗号之间的子串可能会有所不同。但是逗号序列是固定的。例如下面是另一个gps字符串示例,但由于sattellite问题,它不包含它的一些部分:

char gps_string[] = "$GPRMC,001041.799,V,,,,,0.00,0.00,060180,,,N*"

2 个答案:

答案 0 :(得分:3)

您可以使用strtok

#include <stdio.h>

int main(void) {
    char gps_string[] = "$GPRMC,080117.000,A,4055.1708,N,02918.9336,E,0.00,316.26,00,,,A*78";
    char* c = strtok(gps_string, ",");
    while (c != NULL) {
        printf("%s\n", c);
        c = strtok(NULL, ",");
    }
    return 0;
}

编辑:正如Carey Gregory所说,strtok修改了给定的字符串。我在链接到的手册页中对此进行了解释,您也可以找到一些详细信息here

答案 1 :(得分:3)

其他答案中有很多评论指出strtok()存在许多问题,建议使用strpbrk()。可以在Arrays and strpbrk in C

找到如何使用它的示例

我没有可用的编译器,所以我无法测试它。我可能在代码中有拼写错误或其他misteaks,但我相信你可以弄明白是什么意思。

在这种情况下,您将使用

char *String_Buffer = gps_string;
char *start = String_Buffer;
char *end;
char *fields[MAXFIELDS];
int i = 0;
int n = 0;
char *match = NULL;

while (end = strpbrk(start, ",")) // Get pointer to next delimiter 
{
  /* found it, allocate enough space for it and NUL */
  /* If there ar two consecutive delimiters, only the NUL gets entered */
  n = end - start;
  match = malloc(n + 1);

  /* copy and NUL terminate */
  /* Note that if n is 0, nothing will be copied so do not need to test */
  memcpy(match, start, n);
  match[n] = '\0';

  printf("Found field entry: %s\n", match);
  /* Now save the actual match string pointer into the fields array*/
  /* Since the match pointer is in fields, it does not need to be freed */
  fields[i++] = match;
  start = end + 1;
}

/* Check that the last element in the gps_string is not ,
   Then get the final field, which has the NUL termination of the string */
  n = strlen(start);
  match = malloc(n + 1);
  /* Note that if n is 0, only the terminator will be put in */
  strcpy(match, start);
  printf("Found field entry: %s\n", match);
  fields[i++] = match;
  printf("Total number of fields: %d\n", i);