标签:
如题:有一个字符串符合以下特征(”abcdef,acccd,eeee,aaaa,e3eeeee,sssss,";)
思路:用一个二维数组来存储截取后的字符串,以‘ ,‘作为分隔符,截取完一个字符串后,更新当前的位置。直到‘ \0 ‘.
代码:
1 #include <stdlib.h> 2 #include <string.h> 3 #include <stdio.h> 4 int splitString(const char *buf1, char c, char buf2[10][30], int *count) 5 { 6 char *p=NULL, *pTmp = NULL; 7 int tmpcount = 0; 8 //1. p和ptmp初始化 9 p = buf1; 10 pTmp = buf1; 11 do 12 { 13 //2.检索符合条件的位置p后移形成差值挖字符串 14 p = strchr(p, c); 15 if (p != NULL) 16 { 17 if (p-pTmp > 0) 18 { 19 strncpy(buf2[tmpcount], pTmp, p-pTmp); 20 buf2[tmpcount][p-pTmp] = ‘\0‘; //把第一行数据变成 C风格字符串 21 tmpcount ++; 22 //3.重新让p和ptmp达到下一次检索的条件 23 pTmp = p = p + 1; 24 } 25 } 26 else 27 { 28 break; 29 } 30 } while (*p!=‘\0‘); 31 32 *count = tmpcount; 33 return 0; 34 } 35 int main(int argc,char *argv) 36 { 37 int ret = 0, i = 0; 38 char *p1 = "abcdef,acccd,eeee,aaaa,e3eeeee,sssss,"; 39 char cTem= ‘,‘; 40 int nCount; 41 char myArray[10][30]; 42 43 ret = splitString(p1, cTem, myArray, &nCount); 44 45 if (ret != 0) 46 { 47 printf("fucn spitString() err: %d \n", ret); 48 return ret; 49 } 50 for (i=0; i<nCount; i++ ) 51 { 52 printf("%s \n", myArray[i]); 53 } 54 printf("Split complete\n"); 55 return ; 56 }
标签:
原文地址:http://www.cnblogs.com/sxmcACM/p/4436894.html