函数:strsplit
功能:按分割串分割字符串。
参数:from 源串
separators 分割串
pos 段序号,从1开始
to 待存目标串位置
to_size 待存目标串位置长度
返回值:
目标串指针
示例:
char *from = "123 234 456";
char to[10];
strsplit(from, " ", 1, to, sizeof(to)); //得 123
strsplit(from, " ", 4, to, sizeof(to)); //得 NULL
char* strsplit(char *from, const char *separators,
int pos, char *to, int to_size)
{
char *pstart, *pend, *p;
int i;
if (!from || !to) {
return NULL;
}
memset(to, 0, to_size);
if (pos < 1) {
return NULL;
}
pstart = from;
pend = from + strlen(from);
i = 0;
while (pstart) {
i++;
p = strstr(pstart, separators);
if (!p) {
if (i == pos) {
memcpy(to, pstart, MIN(strlen(pstart), to_size-1));
break;
}
else
return NULL;
}
if (i == pos) {
memcpy(to, pstart, MIN(MIN(p-pstart, pend-pstart), to_size-1));
break;
}
pstart = p + strlen(separators);
}
return to;
}
阅读(1039) | 评论(0) | 转发(0) |