繁体   English   中英

在C中拆分字符串:将两部分分开

[英]String split in C: separating the two parts

我有一个字符串LOAD:07.09.30:-40.5&07.10.00:-41.7从网络传入。

我需要检测到它是LOAD:类型,然后根据' & '进行分隔(所以我第一次有07.09.30:-40.5)

然后将07.09.30 (保留为字符串)和-40.5 (转换为float) -40.5

我能够获得-40.5浮动值,但是找不到将07.09.30作为字符串存储的方法。

下面的代码显示输出

tilt angle -40.50
tilt angle -41.70

如何分离和存储07.09.30部分?

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

int main ()
{
   char p[]="LOAD:07.09.30:-40.5&07.10.00:-41.7";
   char loadCmd[]="LOAD:";
   char data[]="";
   int ret;
   int len=strlen (p);
   int i=0, j=0;

   if (!(ret = strncmp(p, loadCmd, 5)))
   { 
      //copy p[5] to p[len-1] to char data[]
      for (i=5;i<len;i++){
         data[j++]=p[i];
      }
      data[j]='\0';
      char *word = strtok(data, "&");  //07.09.30:-40
      while (word != NULL){
         char *separator = strchr(word, ':');
         if (separator != 0){
            separator++;
            float tilt = atof(separator);
            printf("tilt angle %.2f\n", tilt);
         }
         word= strtok(NULL, "&");
      }
   }
   else {
      printf("Not equal\n");
   }
   return(0);
}

在提供解决方案之前,我想指出,不鼓励使用以下代码存储/复制字符串。

char data[]="";
// other codes ...
for (i=5;i<len;i++){
         data[j++]=p[i];
      }

这将破坏堆栈中的内存。 如果在上面的代码之后在loadCmd中打印出该值,您将明白我的意思是什么。

我建议在复制字符串之前分配所需的内存。 以下是动态分配内存的方法之一。

char *data = NULL;
// other codes ...
data = (char *)malloc((len-5+1)*sizeof(char));
// for-loop to copy the string

更改之后,解决方案将很简单。 只需在while循环内定义一个char数组,然后逐个分配单词中的字符,直到命中':'。 一个例子如下所示。

 // inside the while-loop
         char first_part[20];
         i = 0;
         while (word[i] != ':')
         {
           first_part[i] = word[i];
           i++;
         }
         first_part[i] = '\0';
         printf("first part: %s\n", first_part);
         // the rest of the code ...
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *storeUpto(char *store, const char *str, char ch){
    while(*str && *str != ch){
        *store++ = *str++;
    }
    *store = '\0';
    return (char*)(ch && *str == ch ? str + 1 : NULL);
}

int main (void){
    char p[] = "LOAD:07.09.30:-40.5&07.10.00:-41.7";
    char loadCmd[] = "LOAD:";
    char date1[9], date2[9], tilt[10];
    float tilt1, tilt2;

    if (!strncmp(p, loadCmd, 5)){
        char *nextp = storeUpto(date1, p + 5, ':');
        nextp = storeUpto(tilt, nextp, '&');
        tilt1 = atof(tilt);
        nextp = storeUpto(date2, nextp, ':');
        //storeUpto(tilt, nextp, '\0');
        tilt2 = atof(nextp);
        printf("date1:%s, tilt1:%.2f\n", date1, tilt1);
        printf("date2:%s, tilt2:%.2f\n", date2, tilt2);
    }
    else {
        printf("Not equal\n");
    }
    return(0);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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