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);
这样,外部看来,没有使用内存分配。