修改字符串数据

时间:2014-07-23 08:02:23

标签: c printf memcpy atof

我想要子串并修改我的字符串(在下面定义)。

char gps[]="$GPGGA,115726.562,4512.9580,N,03033.0412,E,1,09,0,9,300,M,0,M,,*6E";

很快,我想采取并增加Lat,Long数据,这意味着

我的步骤

  1. 将lat信息作为char或float
  2. 将lat(char)转换为float
  3. 将步骤值添加到float
  4. 将lat(float)转换为char作为newlat
  5. 将newlat插入gps []
  6. 的printf
  7.   char substr[10];  //4512.9580 //#number of char
      memcpy(substr,&gps[19],10); //memcpy from gps char start from 19 take 9 char character
      substr[10]='\0';  //I dont know what makes it
      char lat[10]=???  //I dont know how I will take lat data
      float x;      //defined float value
      x=atof(lat);      //convert string to float
      x=x+0.1;      //add step value to float (4513.0580)
      char newlat[10];  //newlat defined
      sprintf(newlat,x);    //convert to float to string
      ????          //I dont know how I can put into gps[]
    

2 个答案:

答案 0 :(得分:0)

试试这个:

char substr[10];
float x;

memcpy(substr,&gps[18],9);
substr[9]='\0';
x=atof(substr);
x=x+0.1;
sprintf(substr,"%.4f",x);
memcpy(&gps[18];substr,9);

答案 1 :(得分:0)

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

int add(char *x, const char *dx){
//Note that this is not a general-purpose
    int ppos1 = strchr(x, '.') - x;
    int ppos2 = strchr(dx, '.') - dx;
    int len2 = strlen(dx);
    //4512.9580
    //+  0.1
    int i = len2 -1;//dx's last char
    int j = ppos1 + (i-ppos2);//x's add position
    int carry = 0;
    for(;i>=0 || (j>=0 && carry);--i, --j){
        if(dx[i]=='.')
            continue;
        int sum = (x[j]-'0')+(i>=0)*(dx[i]-'0')+carry;
        x[j] = sum % 10 + '0';
        carry = sum / 10;
    }
    return carry;
}

int main(){
    char gps[]="$GPGGA,115726.562,4512.9580,N,03033.0412,E,1,09,0,9,300,M,0,M,,*6E $GPRMC,115726.750,A,4002.9675,N,03233.0412,E,173.8,0,071114,003.1,E*72";  int m,k,j,i,n;
    char *field, *rest;
    field = strchr(gps, ',');//1st ','
    field = strchr(field+1, ',')+1;//2nd ',' next(+1) : 3rd field
    rest = strchr(field, ',');//3rd ','
    int substr_len = rest - field;
    char substring[substr_len + 1];
    memcpy(substring, field, substr_len);
    substring[substr_len] = '\0';
    if(add(substring, "0.1")){//Carry occurred
        char newgps[sizeof(gps)+1];
        *field = '\0';
        strcpy(newgps, gps);
        strcat(newgps, "1");
        strcat(newgps, substring);
        strcat(newgps, rest);
        printf("%s\n", newgps);
    } else {
        memcpy(field, substring, substr_len);//rewrite
        printf("%s\n", gps);
    }
    return 0;
}