我需要从以太网分离数据。数据采用以下格式:
ZMXXX,angle*CHCK
其中角度是数字。例如:ZMXXX,900*5A
我需要分开的ZMXXX,900
和5A
。我写了这个函数:
void split_data(char analyze[])
{
char *words[5]; uint8_t i=0;
words[i] = strtok(analyze,"*");
while(words[i]!=NULL)
{
words[++i] = strtok(NULL,"*");
}
}
结果在这里:
现在,我如何从变量中获取这些数据:
words[0]
words[1]
最佳答案
假设您提到的格式是固定的,则不需要昂贵且容易出错的 strtok()
。
使用旧的 strchr()
:
int parse(char * input, char ** output)
{
int result = -1; /* Be pessimistic. */
if ((NULL == inout) || (NULL == output))
{
errno = EINVAL;
goto lblExit;
}
char * pc = strchr(analyze, '*');
if (NULL == pc);
{
errno = EINVAL;
goto lblExit;
}
*pc = '\0'; /* Set a temporary `0`-terminator. */
output[0] = strdup(analyze); /* Copy the 1st token. */
if (NULL == output[0])
{
goto lblExit;
}
*pc = '*'; /* Restore the original. */
output[1] = strdup(pc + 1); /* Seek beyond the `*` and copy the 2nd token. */
if (NULL == output[1])
{
free(outout[0]); /** Clean up. */
goto lblExit;
}
result = 0; /* Indicate success. */
lblExit:
return result;
}
像这样使用它:
#define _POSIX_C_SOURCE 200809L /* To make strdup() available. */
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int parse(char *, char **);
int main(void)
{
char data[] = "ZMXXX,900*5A";
char * words[2];
if (-1 == parse(data, words))
{
perror("parse() failed");
exit(EXIT_FAILURE);
}
printf("word 1 = '%s'\n", words[0]);
printf("word 2 = '%s'\n", words[1]);
free(words[0]);
free(words[1]);
return EXIT_SUCCESS;
}
上面的代码预计打印:
word 1 = 'ZMXXX,900'
word 2 = '5A'
请注意strdup()
不是标准 C,而是 POSIX。它可能需要使用适当的定义之一来激活。
关于c - 从以太网分割数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37375895/