如何在特定字符后剪切字符串?

时间:2018-01-30 18:28:59

标签: c string

我最近被要求使用c来确定DMEA代码中的某些坐标。代码的一个例子是:

  

$ GPGGA,181908.00,3404.7041778,N,07044.3966270,W,4,13,1.00,495.144,男,29.200,男,0.10,0000 * 40。

我需要在每个逗号后删除部分内容。任何人都知道怎么做C?

1 个答案:

答案 0 :(得分:0)

如果您的记录格式已修复,则可以方便地使用* scanf例程来读取记录。它还将进行必要的数字转换。以下是您的字符串示例:

#include <stdio.h>
#include <string.h>

typedef struct Rec {
    char var [128];
    float x1, x2, x3, x4, x5, x6, x7, x8;
    int i1, i2, i3;
    char c1, c2, c3, c4;
} Rec; // Rename fields to something meaningful

int read_rec(Rec *o, const char *s)
{
    int n = sscanf(s,
        "%[^,],%f,%f,%c,%f,%c,%d,%d,%f,%f,%c,%f,%c,%f,%d*%f",
      &o->var, &o->x1, &o->x2, &o->c1, &o->x3, &o->c2, &o->i1, &o->i2, &o->x4,
      &o->x5, &o->c3, &o->x6, &o->c4, &o->x7, &o->i3, &o->x8);
    if (n != 16 /* num of fields */) {
        printf ("Rec struct reading failed after %d field(s) read: %s\n",
        n, s);
        return 0;
    }
    return 1;
}

void print_rec(const Rec *r, FILE *of)
{
    fprintf(of,
        "%s,%f,%f,%c,%f,%c,%d,%d,%f,%f,%c,%f,%c,%f,%d*%f",
      r->var, r->x1, r->x2, r->c1, r->x3, r->c2, r->i1, r->i2, r->x4,
      r->x5, r->c3, r->x6, r->c4, r->x7, r->i3, r->x8);
}

int main() {
    const char *desc = "$GPGGA,181908.00,3404.7041778,N,07044.3966270,W,4,13,1.00,495.144,M,29.200,M,0.10,0000*40.";
    struct Rec rec;
    if (read_rec(&rec, desc))
        print_rec(&rec, stdout);
    return 0;
}