#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
有一个字符串("abcdef,acccd,ddddd,fffff,sdfsd,llokkl,")
写两个函数(API),输出以下结果
第一个API(第二种内存模型)
1)以逗号分隔字符串,形成二维数组,并把结果传出
2)把二维数组行数运算结果也传出
int spitString(const char* str, char c, char buf[10][30], int* count)
第二个API(第三种内存模型)
1)以逗号分隔字符串,形成一个二级指针
2)把一共拆分多少行字符串个数传出
int spitString2(const char* str, char c, char** myp/in/, int* count)
*/
int spitString(const char* str, char c, char buf[10][30], int* count)
{
if (str == NULL || count == NULL)
{
return -1;
}
//str = "abcdef,acccd,ddddd,fffff,sdfsd,llokkl,"
const char* start = str;
char* p = NULL;
int i = 0;
int len = 0;
do
{
p = strchr(start, c);
if (p != NULL)
{
len = p - start;
strncpy(buf[i], start, len);
//结束符
buf[i][len] = 0;
i++;
//重新设置起点位置
start = p + 1;
}
else
{
strcpy(buf[i], start);
i++;
break;
}
} while (*start != 0);
if (i == 0)
{
printf("未找到字符'%c'\n", c);
return -2;
}
*count = i;
return 0;
}
int spitString2(const char* str, char c, char** myp, int* count)
{
if (str == NULL || myp == NULL || count == NULL)
{
return -1;
}
//str = "abcdef,acccd,ddddd,fffff,sdfsd,llokkl,"
char* p = NULL;
const char* start = str;
int len = 0;
int i = 0;
do
{
p = strchr(start, c);
if (p != NULL)
{
len = p - start;
strncpy(myp[i], start, len);
i++;
//重新设置起点
start = p + 1;
}
else
{
strcpy(myp[i], start);
i++;
break;
}
} while (*start != 0);
if (i == 0)
{
printf("未找到字符'%c'\n", c);
return -2;
}
*count = i;
return 0;
}
char** getMem(int m)
{
char** buf = NULL;
buf = (char**)malloc(m * sizeof(char*));
if (buf == NULL)
{
return NULL;
}
for (int i = 0; i < m; i++)
{
buf[i] = (char*)malloc(30 * sizeof(char));
}
return buf;
}
int main()
{
char* p = "abcdef,acccd,ddddd,fffff,sdfsd,llokkl";
char buf[10][30] = { 0 };
char** buf2 = NULL;
int count = 0, count2 = 0;
int ret = 0, ret2 = 0;
ret = spitString(p, ',', buf, &count);
if (ret != 0)
{
printf("spitString error:%d\n", ret);
return ret;
}
for (int i = 0; i < count; i++)
{
printf("buf[%d]:%s\n", i + 1, buf[i]);
}
printf("\n\n");
/*char* q = NULL;
int m = 0;
while (p != 0)
{
if (q = strchr(p, ',') != NULL)
m++;
p++;
}
printf("%d\n", m);*/
buf2 = getMem(6);
ret2 = spitString2(p, ',', buf2, &count2);
if (ret != 0)
{
printf("spitString2 error:%d\n", ret);
return ret;
}
for (int i = 0; i < count2; i++)
{
printf("buf2[%d]:%s\n", i + 1, buf[i]);
}
for (int i = 0; i < count2; i++)
{
free(buf2[i]);
buf2[i] = NULL;
}
if (buf2 != NULL)
{
free(buf2);
buf2 = NULL;
}
printf("\n");
system("pause");
return 0;
}
C语言用二级指针的两种内存模式分别实现字符串分离
最新推荐文章于 2022-09-25 00:50:39 发布