您的位置:首页 > 其它

两个辅助指针变量截取字符串

2015-04-18 10:09 253 查看
如题:有一个字符串符合以下特征(”abcdef,acccd,eeee,aaaa,e3eeeee,sssss,";)

思路:用一个二维数组来存储截取后的字符串,以' ,'作为分隔符,截取完一个字符串后,更新当前的位置。直到' \0 '.

代码:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int splitString(const char *buf1, char c, char buf2[10][30], int *count)
{
char *p=NULL, *pTmp = NULL;
int    tmpcount = 0;
//1. p和ptmp初始化
p = buf1;
pTmp = buf1;
do
{
//2.检索符合条件的位置p后移形成差值挖字符串
p = strchr(p, c);
if (p != NULL)
{
if (p-pTmp > 0)
{
strncpy(buf2[tmpcount], pTmp,  p-pTmp);
buf2[tmpcount][p-pTmp]  = '\0';  //把第一行数据变成 C风格字符串
tmpcount ++;
//3.重新让p和ptmp达到下一次检索的条件
pTmp = p = p + 1;
}
}
else
{
break;
}
} while (*p!='\0');

*count = tmpcount;
return 0;
}
int main(int argc,char *argv)
{
int ret = 0, i = 0;
char *p1 = "abcdef,acccd,eeee,aaaa,e3eeeee,sssss,";
char cTem= ',';
int nCount;
char myArray[10][30];

ret = splitString(p1, cTem, myArray, &nCount);

if (ret != 0)
{
printf("fucn spitString() err: %d \n", ret);
return ret;
}
for (i=0; i<nCount; i++ )
{
printf("%s \n", myArray[i]);
}
printf("Split complete\n");
return ;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: