You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何高效拆分带NUL终止符与分隔符的字符数组?

嘿,这个需求挺常见的,先给你肯定下——你的拆分思路方向是对的,但确实有更简洁高效的实现方式,尤其是处理这种以\0分隔键值对、最后双\0结尾的格式。下面给你梳理优化思路和具体实现:

优化思路与代码实现

核心优化点

  • 零冗余内存操作:不用额外复制子串,直接通过指针偏移定位key和value的起止位置,减少内存开销和泄漏风险
  • 单次遍历完成:一次扫描字符串就能拆分所有键值对,避免多次扫描的性能损耗
  • 鲁棒性处理:兼容键值对中=后带空格的情况,同时能识别格式不合法的条目

具体代码实现

#include <stdio.h>
#include <string.h>

// 定义键值对结构体,存储指针和长度(避免额外截取子串)
typedef struct {
    const char* key;
    const char* value;
    size_t key_len;
    size_t value_len;
} KeyValuePair;

void parse_key_value(const char* str) {
    const char* current = str;
    
    // 循环终止条件:遇到连续两个\0(当前字符是\0,下一个也是\0)
    while (!(*current == '\0' && *(current + 1) == '\0')) {
        // 定位当前键值对里的=符号
        const char* eq_pos = strchr(current, '=');
        if (!eq_pos) {
            // 处理格式错误的条目,直接跳过
            printf("⚠️ Invalid key-value pair: %s\n", current);
            current += strlen(current) + 1;
            continue;
        }

        // 提取key:从current到eq_pos的前一位
        KeyValuePair pair;
        pair.key = current;
        pair.key_len = eq_pos - current;
        
        // 跳过=和后面可能的空格(兼容格式不严谨的情况)
        const char* value_start = eq_pos + 1;
        while (*value_start == ' ') {
            value_start++;
        }
        
        // 提取value:从value_start到当前\0的前一位
        pair.value = value_start;
        pair.value_len = strlen(value_start);

        // 打印键值对(这里可以换成存储到数组等业务逻辑)
        printf("Key: ");
        fwrite(pair.key, 1, pair.key_len, stdout);
        printf("\nValue: ");
        fwrite(pair.value, 1, pair.value_len, stdout);
        printf("\n\n");

        // 跳到下一个键值对的起始位置
        current += strlen(current) + 1;
    }
}

int main() {
    char str[] = "line 1 = But I set fire to the rain\0line 2 = Watched it pour as I touched your face\0line 3 = Well, it burned while I cried\0line 4 = 'Cause I heard it screaming out your name, your name!\0\0";
    parse_key_value(str);
    return 0;
}

额外优化建议

  • 如果需要长期存储所有键值对,可以先遍历一次统计条目数量,再一次性分配数组内存,避免动态扩容的开销
  • 如果你的业务场景中key或value可能包含=字符,可以约定转义规则(比如用\=表示实际的=),这时候需要在解析时处理转义逻辑

内容的提问来源于stack exchange,提问作者CIsForCookies

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:39:58