目的:将{"channelnum":"8","msg":"01"}中的8和1单独取出来。
#include <stdio.h>
#include <string.h>int charToInt(char *msg, int len)
{
char temp='0';
int i=0,num=0;
char *s = msg;
for(i=0; i<len; i++)
{
temp = *s++;
if(temp>'9' || temp <'0')
continue;
if((num!=0)||(temp != '0'))
{
temp -=0x30;
num+=num*10+temp;
}
}
return num;
}
void channelnum_fun(char *str)
{
char *msg[2]={0};
int aa[2]={0}, leng[2]={0};
int i=0;
msg[i] = strtok(str, ",");//以逗号进行分割,因为这是两条消息数据。
while(msg[i]!= NULL)
{
i++;
msg[i] = strtok(NULL, ",");
}
printf("%s \n %s\n",*msg, *(msg+1));
for(i=0; i<2; i++)
{
leng[i] = strlen(*(msg+i));
aa[i] = charToInt(*(msg+i), leng[i]);
printf("%d\t",aa[i]);
}
}
int main(void)
{
char str[]="{\"channelnum\":\"8\",\"msg\":\"01\"}";
printf("%s\n",str);
channelnum_fun(str);
return 0;
}
虽然这中操作在网络很多,写这篇文章是让自己回顾一下。不喜勿喷。