功能:按一个字符来拆分字符串
参数 src:要拆分的字符串
参数 delim:按照这个字符来拆分字符串
参数 istr:借助这个结构体来返回给调用者拆分后的字符串数组和字符串的个数
返回拆分是否成功
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char **str; //the PChar of string array
size_t num; //the number of string
}IString;
/** \Split string by a char
*
* \param src:the string that you want to split
* \param delim:split string by this char
* \param istr:a srtuct to save string-array's PChar and string's amount.
* \return whether or not to split string successfully
*
*/
int Split(char *src, char *delim, IString* istr)//split buf
{
int i;
char *str = NULL, *p = NULL;
char **data;
(*istr).num = 1;
str = (char*)calloc(strlen(src)+1,sizeof(char));
if (str == NULL) return 0;
data = (char**)calloc(1,sizeof(char *));
if (data == NULL) return 0;
str = src;
data[0] = strtok(str, delim);
for(i=1; p = strtok(NULL, delim); i++)
{
(*istr).num++;
data = (char**)realloc(data,(i+1)*sizeof(char *));
if (data == NULL) return 0;
data[i] = p;
}
(*istr).str = data;
free(str);
free(p);
//free(data); //You must to free it in the caller of function
str = p = NULL;
return 1;
}
int main()
{
int i;
char s[]="data0|data1|data2|data3|data4|data5|data6|data7|data8";
IString istr;
if ( Split(s,"|",&istr) )
{
for (i=0;i<istr.num;i++)
printf("%s\n",istr.str[i]);
free(istr.str); //when you don't ues it,you must to free memory.
}
else
printf("memory allocation failure!\n");
system("pause");
return 0;
}
运行结果:
data0
data1
data2
data3
data4
data5
data6
data7
data8
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/lell3538/article/details/48011135