簡體   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