C语言按子串分割字符串
一、按字符分割字符串
C语言提供了一个按字符分割字符串的库函数
char *strtok(char *str, const char *delim)
分解字符串 str 为一组字符串,delim 为分隔符。
参数
str : 要被分解成多个小字符串的字符串。
delim :分隔符。
返回值
该函数返回被分解的第一个子字符串,如果没有可检索的字符串,则返回一个空指针。
通过对该函数封装,获得按字符分割字符串的函数,该函数代码为copy过来的,原文地址忘记了。。。
/*按字符分割src 源字符串的首地址(buf的地址) separator 指定的分割字符dest 接收子字符串的数组num 分割后子字符串的个数*/void split(char *src,const char *separator,char **dest,int *num) { char *pNext; int count = 0; if (src == NULL || strlen(src) == 0) //如果传入的地址为空或长度为0,直接终止 return; if (separator == NULL || strlen(separator) == 0) //如未指定分割的字符串,直接终止 return; pNext = (char *)strtok(src,separator); //必须vps云服务器使用(char *)进行强制类型转换(虽然不写有的编译器中不会出现指针错误) while(pNext != NULL) { *dest++ = pNext; ++count; pNext = (char *)strtok(NULL,separator); //必须使用(char *)进行强制类型转换 } *num = count;}
二、按字符串分割字符串
在长字符串中根据给定短字符串分割字符串代码
/*在长字符串中根据给定短字符串分割字符串,需要在外部声明指向指针变量的数据,获取数据后在外部free掉input:输入长串splitstr:输入子串output:保存输出结果num:子串个数*/int StrSplit(char * input, char* splitstr, char ** output, int *num){int tmplen = 0;int totallen = 0;int count = 0;int nRtn = 0;char *p = input;int nSrcLen = strlen(input);int nSplStrLen = strlen(splitstr);if (input == NULL || nSrcLen == 0) //如果传入的地址为空或长度为0,直接终止 {return -1;} if (splitstr == NULL || nSplStrLen == 0) //如未指定分割的字符串,直接终止 {return -1;}//若第一个字符与短串相同,按短串长度比较while((*p != ‘\0’)){if (*p == splitstr[0]){if (0 == strncmp(p, splitstr, nSplStrLen)){//开辟内存,地址放在output[count]中output[count] = (char*)malloc(tmplen+1);//把分割出的字串拷贝到output[count]内存中strncpy(output[count], input + totallen, tmplen);//添加截止符(output[count])[tmplen] = ‘\0’;//printf(“output[%d]: [%s]\n”, count, output[count]);//字串个数加一count++;//p移动的长度增加totallen += (tmplen + nSplStrLen);//p指向新的地址p += nSplStrLen;//下个字串长度tmplen = 0;continue;}}p++;tmplen++;}//最后一个字串output[count] = (char*)malloc(tmplen+1);strncpy(output[count], input + totallen, tmplen);(output[count])[tmplen] = ‘\0’;//printf(“output[%d]: [%s]\n”, count, output[count]);count++;*num = count;return 0;}
详细注释都在代码中,使用方法:
int main(){int i;int num = 0;char *apbyRtn[5] = {0};//指针类型的数组,每个元素保存一个指针,必须足够大char str1[]=”12345679—split—www.taobao.com—split—www.csdn.com”;char str2[] = “—split—“;printf(“str1:\n%s\n”, str1);printf(“str2:\n%s\n”, str2);printf(“*************************************************************\n”);//分割StrSplit(str1, str2, apbyRtn, &num);//获取结果并释放for (i = 0; i < num; i++){printf(“apbyRtn[%d] = %s\n\n”, i, apbyRtn[i]);free(apbyRtn[i]);}printf(“num = %d\n”, i, num);return 0;}
需要注意的是在调用分割函数后,根据子串的个数,分别释放内存。运行结果如下:
str1:12345679—split—www.taobao.com—split—www.csdn.comstr2:—split—*************************************************************apbyRtn[0] = 12345679apbyRtn[1] = www.taobao.comapbyRtn[2] = www.csdn.comnum = 3 14829643