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

C语言实现指定起止字符串间子串提取的技术求助

实现C语言子串提取函数

我来帮你搞定这个extractSubstring函数,完全贴合你的需求。先上完整可运行的代码,再给你拆解每一步的逻辑:

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

// 兼容你代码里的bool定义
typedef int bool;
#define true 1
#define false 0

/**
 * 提取起始字符串与结束字符串之间的子串
 * @param source 源字符串
 * @param dest 存储结果的目标缓冲区
 * @param start_str 起始匹配字符串
 * @param end_str 结束匹配字符串
 * @param include_start 是否包含起始字符串
 * @return 成功返回提取的子串长度,失败返回-1
 */
int extractSubstring(const char* source, char* dest, const char* start_str, const char* end_str, bool include_start) {
    // 1. 找到起始字符串的位置
    const char* start_pos = strstr(source, start_str);
    if (start_pos == NULL) {
        // 找不到起始串,直接返回失败并清空目标缓冲区
        *dest = '\0';
        return -1;
    }

    // 2. 调整起始指针:是否包含起始串
    const char* sub_start;
    if (include_start) {
        sub_start = start_pos;
    } else {
        sub_start = start_pos + strlen(start_str);
    }

    // 3. 从sub_start开始找结束字符串的位置
    const char* end_pos = strstr(sub_start, end_str);
    if (end_pos == NULL) {
        // 找不到结束串,默认提取到源字符串末尾
        end_pos = source + strlen(source);
    }

    // 4. 计算子串长度,安全复制到目标缓冲区
    size_t sub_len = end_pos - sub_start;
    strncpy(dest, sub_start, sub_len);
    dest[sub_len] = '\0'; // 手动添加字符串终止符

    return (int)sub_len;
}

int main() {
    char source[100] = "Some random text with $$KEY:value$$";
    char dest[12]; // 足够存"value"和终止符

    int result = extractSubstring(source, dest, "KEY:", "$", false);
    if (result != -1) {
        printf("提取到的子串:%s\n", dest); // 输出应该是"value"
    } else {
        printf("提取失败\n");
    }

    // 测试包含起始串的情况
    char dest2[20];
    extractSubstring(source, dest2, "KEY:", "$", true);
    printf("包含起始串的结果:%s\n", dest2); // 输出"KEY:value"

    return 0;
}

关键逻辑拆解

  • 定位起始点:用strstr快速定位起始字符串在源串中的位置,找不到就直接返回失败并清空目标缓冲区,避免垃圾数据。
  • 调整子串起点:根据include_start标志灵活调整子串的起始位置——不需要包含起始串时,直接跳转到起始串的末尾。
  • 定位结束点:从调整后的起点开始找结束串,要是找不到结束串,就默认提取到源串的最后一个字符。
  • 安全复制:用strncpy避免缓冲区溢出,最后手动添加'\0'(因为strncpy在复制长度等于缓冲区大小时不会自动添加终止符)。

可选优化建议

  • 如果需要更严格的缓冲区安全,可以给函数加一个dest_size参数,复制前检查sub_len + 1是否小于等于dest_size,彻底避免越界。
  • 目前实现区分大小写,要是需要不区分大小写的匹配,可以自己实现一个strcasestr(部分编译器自带,也能手动编写)替换strstr。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:46:22