仿split函数:
bool cutApart(const char* in, char*** out, char delimiter, int fragments)
{
int i;
char* p;
char** pstart;
char* space = (char*)calloc(strlen(in), sizeof(char));
strcpy(space, in);
if(!fragments)
{//如果值为0,不限制片段数目
}
pstart = (char**)calloc(fragments, sizeof(char*));
for(i=1,pstart[0]=space,p=space; i<fragments; i++)
{
p = strchr(p,delimiter);
if(!p) return false;
*p = 0;
p++;
pstart[i] = p;
}
if( strchr(p,delimiter) ) return false;
*out = pstart;
return true;
}
Test:
void test_cutApart()
{
char** p;
int i,j;
int f = 0;
char s[3][20]={"192.168.25.90","",".100."};
for (j=0;j<3;j++)
{
if( cutApart(s[j], &p, '.',&f) )
{
for(i=0; i<f; i++)
{
if (i == 0) printf("<");
printf("%s",*p);
if (i == f-1) printf(">\n");
else printf("|");
*p = NULL;
p++;
}
//free(p);
p = NULL;
}
f = 0;
}
}
Result:
<192|168|25|90>
<>
<|100|>