您的位置:首页 > 编程语言 > C语言/C++

c语言练习(4)--逗号分割字符串形成二维数组

2017-06-12 22:30 531 查看
/**
作者:一叶扁舟
时间:23:11 2017/6/4
作用:
有一个字符串符合以下特征(”abcdef,acccd,eeee,aaaa,e3eeeee,sssss";),要求写一个函数(接口),输出以下结果
1)以逗号分割字符串,形成二维数组,并把结果传出;
2)把二维数组行数运算结果也传出。
strchr(“aa,aa”,’,’ );
请自己定义一个接口(函数)。
要求1:能正确表达功能的要求,定义出接口(函数)(30分);
要求2:正确实现接口(函数),并实现功能(40分);
要求3:编写正确的测试用例。(30分)。
**/

#include<stdio.h>
#include <stdlib.h>
#include <string.h>

//获取总共要分几行
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");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  分割字符串