有一个字符串符合以下特征(”abcdef,acccd,eeee,aaaa,e3eeeee,sssss,”;),要求写一个函数(接口),输出以下结果
1) 以逗号分割字符串,形成二维数组,并把结果传出;
2) 把二维数组行数运算结果也传出。
int getStrArray(const char *src, char dst[100][100])
{
int i = 0,j = 0, nLength = 0;
char *curStart = src;
char *lastStart = src;
do
{
curStart = strstr(curStart, ",");
nLength = curStart - lastStart;
memcpy(dst[i++], lastStart, nLength);
lastStart = ++curStart;
} while (*curStart != '\0');
return 0;
}
int main()
{
char *src = "abcdef,acccd,eeee,aaaa,e3eeeee,sssss,";
char dst[100][100] = {0};
getStrArray(src, dst);
return 0;
}
还可以用另外一种二维指针模型来实现 二维指针共有三种
void printfArr(char **arrayPtr, int nLength) { int i = 0; for (; i < nLength; i++) { printf("%s\n", arrayPtr[i]); } } int getStrArray(const char *src, char **dst) { int i = 0,j = 0, nLength = 0; char *curStart = src; char *lastStart = src;
do { curStart = strstr(curStart, ","); nLength = curStart - lastStart; memcpy(dst[i++], lastStart, nLength); lastStart = ++curStart; } while (*curStart != '\0'); return 0;
}
int main()
{
int j = 0;
int i =0;
char *src = “abcdef,acccd,eeee,aaaa,e3eeeee,sssss,”;
char dst = (char )malloc(10 * sizeof(char *));if (!dst) { return -1; } for (; i < 10; i++) { dst[i] = (char *)malloc(100); memset(dst[i],'\0',100); } getStrArray(src, dst); printfArr(dst, 10); for (i = 0; i < 10; i++) { free(dst[i]); } free(dst); return 0;
}
//获取总共要分几行
void getLine(char *str, char c, int *line){
char *p = str;
char *q = str;
int num = 0;
while (*p != ‘\0’){
if (*p == c){
num++;
}
p++;
}
num = num + 1;
*line = num;
}
char ** getData(char *str, char c, int line){
char *p = str;
char *q = str;char **result = (char **)malloc(line*sizeof(char*)); for (int i = 0; i < line; i++){ while (*q != '\0' && *q != c){//没有到字符串的结尾或者遇到分割符c q++; } char *part = (char *)malloc(100 * sizeof(char)); int length = q - p; memcpy(part, p, length);//拷贝数据 part[length] = '\0'; p = q + 1 ; q = q + 1; result[i] = part; } return result;
};
void main(){
char *str =”abcdef,acccd,eeee,aaaa,e3eeeee,sssss”;
int line = (int )malloc(1*sizeof(int));
char c = ‘,’;
getLine(str, c, line);
printf(“%s字符串可以分%d行\n”,str,*line);
char ** result = getData(str, c, *line);
printf(“分割的字符串数组数据:\n”);
for (int i = 0; i < *line; i++){
printf(“%s\n”,result[i]);
}
system(“pause”);
}