#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
按照特定字符截取字符串
(in)scr 源字符串
(in)sign 特定字符
(in)index 截取字符串的下标 从1开始
*/
char * S_trtok(char *scr,char sign,int index)
{
char * tar = (char *)malloc(100); //开辟堆空间
int i = 0;
int flag = 0;
int startpos = 0;
int endpos = 0;
while(scr[i] != '\0')
{
if(scr[i] == sign)
{
flag++;
if(flag == index - 1)
{
startpos = i+1;
}
if(flag == index)
{
endpos = i;
}
}
i++;
}
if(endpos == 0) //用于查找最后一个,此时字符串末尾的'\0'可以当做','
{
endpos = i;
}
strncpy(tar,scr+startpos,endpos-startpos);
return tar;
}
int main()
{
char * a = "9600,N,8,15345345634";
char * b = S_trtok(a,',',1); //获取第一个截取的字符串
char * c = S_trtok(a,',',2);
char * d = S_trtok(a,',',3);
char * e = S_trtok(a,',',4);
printf("%s\n",b);
printf("%s\n",c);
printf("%s\n",d);
printf("%s\n",e);
free(b); //记得释放空间
free(c);
free(d);
free(e);
return 0;
}