C语言 字符串库 strs
由于C标准库中的字符串处理函数功能太少了,因此自己参照这Go语言标准库的strings包的API的功能,用C语言写了一个。
cstrs地址: https://github.com/duapple/cstrs
https://gitee.com/duapple/cstrs
这里展示其中一个字符串分割的API。
char **strs_split(const char *str, const char *sep, int *num)
{
CHECK_RET_PTR(str && sep && num);
size_t size1 = strlen(str);
size_t size2 = strlen(sep);
char **strList = NULL;
if (size2 == 0) {
strList = chcm_strsloc2(size1, 2);
for (int i = 0; i < size1; i++) {
strList[i][0] = str[i];
}
*num = size1;
return strList;
}
int cnt = strs_count(str, sep);
if (cnt <= 0) {
strList = chcm_strsloc2(1, size1 + 1);
memcpy(strList[0], str, size1);
*num = 1;
return strList;
}
strList = phook.calloc(cnt + 1, sizeof(char *));
int pos = 0;
int index = strs_index(str, sep);
int i = 0;
for (;;) {
if (index >= 0) {
strList[i] = chcm_strsloc(index + 1);
strncat(strList[i], str + pos, index);
pos = pos + index + size2;
index = strs_index(str + pos, sep);
i++;
} else {
strList[i] = chcm_strsloc(size1 - pos + 1);
strcat(strList[i], str + pos);
break;
}
}
*num = cnt + 1;
return strList;
}
使用示例:
#include <stdio.h>
#include <string.h>
#include "strs.h"
int main()
{
char buf[128] = {0};
char *str2 = NULL;
char *str3 = NULL;
int num = 0;
char **str4 = NULL;
str2 = strs_join_n(" ", "Today", "is", "a", "funny", "day", "!", NULL);
str3 = strs_dup(str2); // 拷贝str2,会为str3分配合适内存
println("str2: %s", str2);
println("");
strs_dup2(buf, 128, str2); // 拷贝str2,并释放str2内存
println("buf: %s", buf);
println("");
num = -1; // num为分割的数量,小于0时,分割全部(等于strs_split)
str4 = strs_split_n(str3, " ", &num);
for (int i = 0; i < num; i++) {
printf("splits %d: %s\n", i, str4[i]);
}
strs_free2(str4, num);
strs_free(str3);
println("");
}
运行结果:
duapple@duapple-vm:~/linuxdata/test/cstrs_test$ ./test
str2: Today is a funny day !
buf: Today is a funny day !
splits 0: Today
splits 1: is
splits 2: a
splits 3: funny
splits 4: day
splits 5: !
拼接字符串时还可以这样写:
char buf[128] = {0};
strs_dup2(buf, 128, strs_join_n(" ", "Today", "is", "a", "funny", "day", "!", NULL);
这样,外部看来,没有使用内存分配。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· 因为Apifox不支持离线,我果断选择了Apipost!