用strstr()写的一Split分割函数(解决strtok分割问题)
strtok 会将 "a,b,,c,,,,d,e" 中的",,"做一个","给处理
/*
功能:返回第nPos个 (从0开始) needle分割串
参数说明:
haystack :待处理的串
needle :分割串
nPos:返回第几个处理结果
szParResult:接收结果的Buff
*/
void split(char* haystack,char* needle,int nPos,char* szParResult)
{
int NSZIE = 200;
char arr[512];
char *val = (char*)malloc(NSZIE);
memset(arr,0,sizeof(arr));
memset(val,0,sizeof(char)*NSZIE);
memcpy(arr,haystack,strlen(haystack));
int nCnt = -1;
char* buf = strstr(haystack, needle);
while(buf != NULL )
{
nCnt++;
memcpy(val,arr,strlen(haystack)-strlen(buf));
if(nPos == nCnt)
{
memcpy(szParResult,val,strlen(val));
free(val);
return ;
}
//printf("%s/n",val);
haystack = buf + strlen(needle);
buf = strstr(haystack, needle);
memset(arr,0,sizeof(arr));
memcpy(arr,haystack,strlen(haystack));
memset(val,0,sizeof(char)*NSZIE);
}
memset(val,0,sizeof(char)*NSZIE);
memcpy(val,haystack,strlen(haystack));
memcpy(szParResult,val,strlen(val));
free(val);
return;
}
/*
功能:统计needle分割后串的个数
参数说明:
haystack :待处理的串
needle :分割串
*/
int countToken(char* haystack,char* needle)
{
char* buf = haystack;
int cnt = 0;
while(buf!=NULL)
{
char* tmp = NULL;
tmp = strstr(buf,needle);
buf = tmp;
if(buf!=NULL)
buf += strlen(needle);
cnt++;
}
if(cnt==0)
{
cnt = 1;
}
return cnt;
}
void main()
{
char* haystack = "AA%%BB%C%D%%%%%E%F";
char* needle ="%%";
char result[200];
memset(result,0,sizeof(result));
for(int i=0;i<countToken(haystack ,needle );i++)
{
printf("==%d, %s/n", i,split(haystack,needle,i,result);
memset(result,0,sizeof(result));
}
}
//上面的效率太低了,下面这个是返回一个二维数组
bool StrSplit(char* haystack, char* needle, char *szArr, int colSize, int& count)
{
if ((haystack == NULL) || (needle == NULL) || (szArr == NULL))
{
return false;
}
int nCnt = 1;
char* buf = haystack;
char* tempBuf = NULL;
char *szArrRes = szArr;
tempBuf = strstr(buf,needle);
if(tempBuf == NULL)
{
memcpy(szArrRes,buf,strlen(buf));
}
else
{
memcpy(szArrRes,buf,strlen(buf)-strlen(tempBuf));
}
while(tempBuf != NULL)
{
nCnt++;
szArrRes = szArrRes+colSize;
char* temp = NULL;
tempBuf = tempBuf + strlen(needle);
temp = strstr(tempBuf,needle);
if(temp != NULL)
{
memcpy(szArrRes,tempBuf,strlen(tempBuf)-strlen(temp));
}
else
{
memcpy(szArrRes,tempBuf,strlen(tempBuf));
}
tempBuf = temp;
}
count = nCnt;
return true;
}
int main(int argc, char* argv[])
{
char *haystack="%%12%%22%%23%%33%%44%%55%%0%%0%%1%%";
char *needle="%%";
char a[100][100];
memset(a,0,sizeof(a));
int cnt = 0;
bool b = StrSplit(haystack,needle, (char*)a,100,cnt);
for(int i=0; i<cnt; i++)
{
printf("i:%d %s/n",i, a[i]);
}
return 0;
}