c语言输出时如何分割字符,使用C语言实现字符串分割

本文介绍了如何使用C语言实现字符串分割函数splitstr_c,该函数接受一个字符串和分隔符,返回一个char**类型的字符串数组和一个表示数量的整数。文章通过示例展示了如何使用和释放该函数的结果,并给出了打印和释放字符串数组的辅助函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前分享了一篇使用C++(std::string 作为容器)进行字符串分割的博文:

https://blog.csdn.net/r5014/article/details/82802664

现在又想用C语言做一个字符串分割的函数,大概功能是这样:

需要分割的字符串“    this is a charactor  raw.    ” 使用 ' '分割

分割之后会返回一个char** strv 表示分割出子串str的vector,返回一个int strc表示分割出子串的数量,在使用完毕之后自行释放strv

strv可能是NULL 比如"      "使用‘ ’分割之后就是NULL。

以下介绍分割函数splitstr_c()

//* 切割字符串,strv返回字符串数组,strc返回分割之后的字符串数量

void splitstr_c(char* str, char c, char*** strv, int* strc)

{

int i = 0;

int j = 0;

int n = 0;

int offset_strv = 0;

int offset_font = 0;

int offset_back = 0;

int str_size = strlen(str);

char** tstrv = NULL;

for(i = 0; i < str_size; i++)

{

if(i > 0)

{

if((str[i] != c) && (str[i - 1] == c))

{

n++;

}

}

else

{

if(str[0] != c)

{

n++;

}

}

}

if(n == 0)

{

for(i = 0; i < str_size; i++)

{

if(str[i] != c)

{

n++;

break;

}

}

}

* strc = n;

tstrv = (char**)malloc(sizeof(char*) * n);

memset(tstrv, 0, sizeof(char*)*n);

for(i = 0; i < str_size; i++)

{

if(str[i] == c)

{

offset_back = i;

if(offset_back != offset_font)

{

n = offset_back - offset_font;

char* sub_str = (char*)malloc(sizeof(char) * (n + 1)); //* n + 1是为了容纳'\0'

memset(sub_str, 0, sizeof(char) * (n + 1));

memcpy(sub_str, str + offset_font, n);

tstrv[offset_strv] = sub_str;

offset_strv++;

}

offset_font = offset_back + 1;

}

}

if(offset_back < str_size)

{

offset_back = str_size;

if(offset_back != offset_font)

{

n = offset_back - offset_font;

char* sub_str = (char*)malloc(sizeof(char) * (n + 1));

memset(sub_str, 0, sizeof(char) * (n + 1));

memcpy(sub_str, str + offset_font, n);

tstrv[offset_strv] = sub_str;

offset_strv++;

}

offset_font = offset_back + 1;

}

* strv = tstrv;

}

顺带给出两个小工具函数:

//* print strv

void print_strv(char** strv, int strc)

{

if(strc > 0)

{

for(int i = 0; i < strc; i++)

{

printf("%s\n",strv[i]);

}

}

}

//* strv使用完之后根据strc来进行释放。

void free_strv(char** strv, int strc)

{

if(strc > 0)

{

for(int i = 0; i < strc; i++)

{

//printf("%s\n",strv[i]);

free(strv[i]);

}

free(strv);

}

}

让我们来试一下:

char *text = " this is a charactor text. ";

//char *text = "000this00is0a0charactor0text.00";

//char *text = "this is a charactor text.";

//char *text = "a a a a s ";

char** strv = NULL;

int strc = 0;

splitstr_c(text, ' ', &strv, &strc);

printf("splitstr_c: %d\n", strc);

print_strv(strv, strc);

free_strv(strv, strc);

结果:

5ffe22cdd0de99c9ec4f1c1313e8f633.png

自此这个功能就实现了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值