風之力

导航

C语言的split功能

其它高级语言都有字符串的split功能,但C没有系统自带的,只能自己写一个了。
void c_split(char *src, const char *separator, int maxlen, char **dest, int *num)
{
char *pNext;
int count = 0;
if (src == NULL || strlen(src) == 0)
return;
if (separator == NULL || strlen(separator) == 0)
return;
pNext = strtok(src, separator);
while (pNext != NULL && count < maxlen) {
*dest++ = pNext;
++count;
pNext = strtok(NULL, separator);
}
*num = count;
}
用法:
#define MAX_LEN 3
const char* msg = "a,b,c,d,e,f,g,h";
int num = 0;
char *split_buf[MAX_LEN ] = {0};
int i = 0;
c_split(msg, ",", MAX_LEN , split_buf, &num);
for(i=0;i {
if(i >= num) break;
cout << split_buf[i] << endl;
}

posted on 2018-12-10 10:06  ZY.Zhou  阅读(1262)  评论(0编辑  收藏  举报