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);

这样,外部看来,没有使用内存分配。

2023-12-25 update:
使valgrind完成内存泄露测试,strs_fields api 分配了buff的内存没有释放,其他api无内存泄露。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值