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

C语言实现多分隔符字符串拆分:支持字符与字符串分隔符

多分隔符字符串拆分的C语言实现

要实现支持单个字符和字符串作为分隔符的字符串拆分功能,我们可以设计一套通用处理逻辑:遍历目标字符串,逐个检查当前位置是否匹配任意分隔符,匹配成功则提取之前的有效子串,最终输出所有非空的拆分结果。

代码实现

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

// 定义分隔符类型:字符或字符串
typedef enum {
    DELIM_CHAR,
    DELIM_STR
} DelimType;

// 分隔符结构体,统一管理不同类型的分隔符
typedef struct {
    DelimType type;
    union {
        char c;
        char *str;
    } value;
} Delimiter;

// 跳过字符串开头的空白字符
char* skip_whitespace(char *s) {
    while (isspace((unsigned char)*s)) s++;
    return s;
}

// 检查当前位置是否匹配指定分隔符,返回匹配的长度
int match_delim(char *s, Delimiter *delim) {
    if (delim->type == DELIM_CHAR) {
        if (*s == delim->value.c) {
            return 1;
        }
    } else {
        size_t len = strlen(delim->value.str);
        if (strncmp(s, delim->value.str, len) == 0) {
            return len;
        }
    }
    return 0;
}

// 核心拆分函数
void split_string(char *input, Delimiter *delims, int delim_count) {
    char *start = skip_whitespace(input);
    char *current = start;

    while (*current != '\0') {
        int matched_len = 0;
        // 遍历所有分隔符,找到最长的匹配项
        for (int i = 0; i < delim_count; i++) {
            int len = match_delim(current, &delims[i]);
            if (len > matched_len) {
                matched_len = len;
            }
        }

        if (matched_len > 0) {
            // 提取当前子串并去掉末尾空白
            char *end = current - 1;
            while (end >= start && isspace((unsigned char)*end)) end--;
            if (end >= start) {
                printf("%.*s\n", (int)(end - start + 1), start);
            }
            // 跳过分隔符和后续空白,重置起始位置
            current += matched_len;
            start = skip_whitespace(current);
            current = start;
        } else {
            current++;
        }
    }

    // 处理最后一段子串
    if (start < current) {
        char *end = current - 1;
        while (end >= start && isspace((unsigned char)*end)) end--;
        if (end >= start) {
            printf("%.*s\n", (int)(end - start + 1), start);
        }
    }
}

int main() {
    char string[] = "a or b or c, 8";
    // 定义需要使用的分隔符列表
    Delimiter delims[] = {
        {DELIM_STR, {.str = "or"}},
        {DELIM_CHAR, {.c = ','}}
    };
    int delim_count = sizeof(delims) / sizeof(delims[0]);

    split_string(string, delims, delim_count);
    return 0;
}

代码说明

  1. 分隔符管理:通过Delimiter结构体+枚举类型,统一处理字符和字符串两种分隔符,避免重复逻辑。
  2. 空白处理:skip_whitespace函数负责跳过子串前后的空白字符,确保输出结果不含多余空格。
  3. 匹配逻辑:match_delim函数检查当前位置是否匹配指定分隔符,返回匹配长度(字符分隔符返回1,字符串分隔符返回自身长度)。
  4. 拆分流程:遍历输入字符串,匹配到分隔符时提取有效子串并输出,随后跳过分隔符和空白,继续处理剩余内容;最后单独处理末尾的子串。

测试输出

运行代码后,输出结果如下:

a
b
c
8

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 14:45:20