1.一组形如 char* arr = (char*)"dbddcc,asfafa,casdas,casafa,fasass" ;
要求:1,定义一个函数,把字符串按“,”进行分割
2,将分割后的字符串存储到一个数组中返回
3. 返回存储的字符串的列数
int dividStr(const char* initArr,char c,char buf2[5][10],int *count )
{
int ret = 0;
int num = 0;
char* p = initArr;
char* temp = initArr;
if (initArr == NULL || buf2 == NULL || count == NULL)
{
ret = -1;
return ret;
}
while (*p!='\0')
{
if (*p == c)
{
strncpy(buf2[num], temp,p-temp);
//给字符串末尾添加'\0'
buf2[num][p - temp] = '\0';
temp = p +1;
num++;
}
p++;
}
strncpy(buf2[num], temp, p - temp);
buf2[num][p - temp] = '\0';
*count = num+1;
return ret;
}
void main()
{
int i, j;
int ret = 0;
char* arr = (char*)"dbddcc,asfafa,casdas,casafa,fasass" ;
char cTem = ',';
int num = 0;
char myArray[5][10];
ret = dividStr(arr, cTem, myArray, &num);
if (ret != 0)
{
printf("func dividStr error:ret=\n", ret);
}
for (i = 0; i < num; i++)
{
printf("%s\n", myArray[i]);
}
system("pause");
return;
}
2.挖去字符串的进阶版 使用第三种内存模型,并且在被调函数中分配内存,分配的内存空间的大小根据字符串的大小来确定行数和列数。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void freeMemory1(char** myArray, int num)
{
//释放第二层内存
int i;
for (i = 0; i < num; i++)
{
if (myArray[i] != NULL)
{
free(myArray[i]);
myArray[i] = NULL;
}
}
//释放第二层内存
if (myArray != NULL)
{
free(myArray);
myArray = NULL;
}
}
char ** spitArray(char* initArr, char* cTem, char** buf, int *num)
{
int ret = 0;
int count = 0;
if(initArr ==NULL||cTem==NULL)
{
ret = -1;
printf("func spitArray paramter error:ret=\n", ret);
}
char* p = NULL;
char* temp = NULL;
p = initArr;
temp = initArr;
//遍历一次字符串查找出需要分配多少行内存空间
while (*p != '\0')
{
if (*p == *cTem)
{
count++;//用count记录行数
}
p++;
}
count = count + 1;
//根据count的值分配第一层内存空间
buf = (char**)malloc(count * sizeof(char*));
//判断是否分配成功
if (buf == NULL)
{
ret = -1;
printf("(char**)malloc(5 * sizeof(char*)) error:ret=\n", ret);
}
//将指针p重新指向字符串的首地址
p = initArr;
count = 0;
while (*p != '\0')
{
if (*p == *cTem)
{
int len = 0;
len = p - temp;
//根据分割字符串的大小,分配内存空间
buf[count] = (char*)malloc(len * sizeof(char) + 1);
if (buf[count] == NULL)
{
freeMemory1(buf, num);
}
strncpy(buf[count], temp, len);
buf[count][p - temp] = '\0';
temp = p + 1;
count++;
}
p++;
}
buf[count] = (char*)malloc((p-temp) * sizeof(char) + 1);
//如果某个内存分配失败,则需要释放之前分配的所有内存
if (buf[count] == NULL)
{
freeMemory1(buf, num);
}
strncpy(buf[count], temp, p - temp);
buf[count][p - temp] = '\0';
//在buf中保存了0-4,共计5行数据,最后count的值是4,所以需要+1
*num = count+1;
//将buf的地址返回,供主调函数使用
return buf;
}
void main()
{
int i;
int ret = 0;
int num = 0;
char* arr = (char*)"dbddcc,asfafa,casdas,casafa,fasass" ;
char cTem = ',';
char** myArray = NULL;
//调用划分字符串函数
myArray =spitArray(arr, &cTem, myArray, &num);
for (i = 0; i < num; i++)
{
printf("%s\n", myArray[i]);
}
//释放内存
freeMemory1(myArray, num);
system("pause");
return;
}