C中的字符串分割:将两部分分开
问题描述:
我有一个从网络传入的字符串LOAD:07.09.30:-40.5&07.10.00:-41.7
。C中的字符串分割:将两部分分开
我需要检测,这是一个LOAD:
类型,则单独基于“&
”(所以我有30年7月9日:-40.5第一次)
然后分开07.09.30
(保持它作为字符串)和-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);
}
答
#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);
}
+0
不要转储代码。提供意见。 – TisteAndii
答
之前提供的解决方案,我想指出的是,用于存储下面的代码/复制串不鼓励。
char data[]="";
// other codes ...
for (i=5;i<len;i++){
data[j++]=p[i];
}
这会破坏堆栈中的内存。如果你在上面的代码之后打印出laodCmd中的值,你会看到我的意思是什么。
我建议在复制字符串之前分配所需的内存。以下是分配内存(动态)的方法之一。
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 ...
1)'char数据[] = “”;' - >'char数据[的sizeof P] = “”;' – BLUEPIXY
非常密切相关[如何将炭的分裂部件C和转换为浮动?](https://stackoverflow.com/questions/37216938/) - 同样的OP。然而,这是一个不同的,可以说是更好的问题。 –