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

如何将C语言判断命令的if语句转换为switch case并优化?

将字符串命令判断从if-else转换为switch case及优化方案

C语言的switch语句仅支持整型常量表达式作为判断条件,没法直接对字符串做分支判断,所以要实现switch版本的命令判断,需要先对输入字符串做预处理,再结合字符判断来实现。

基于switch的实现方案

我们可以先将输入字符串统一转为小写(或大写),再通过首字母作为switch的分支条件,在每个case内完成完整字符串的匹配:

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

// 辅助函数:将字符串转为小写
void toLowerCase(char *str) {
    while (*str) {
        *str = tolower((unsigned char)*str);
        str++;
    }
}

int getCommand(char *buffer) {
    int action = 0;
    // 临时缓冲区存储处理后的命令,避免修改原输入
    char cmd_buf[16];
    strncpy(cmd_buf, buffer, sizeof(cmd_buf) - 1);
    cmd_buf[sizeof(cmd_buf) - 1] = '\0';
    toLowerCase(cmd_buf);

    switch (cmd_buf[0]) {
        case 's':
            if (strcmp(cmd_buf, "send") == 0) {
                action = 1;
            }
            break;
        case 'l':
            if (strcmp(cmd_buf, "list") == 0) {
                action = 2;
            }
            break;
        case 'r':
            if (strcmp(cmd_buf, "read") == 0) {
                action = 3;
            }
            break;
        case 'd':
            if (strcmp(cmd_buf, "del") == 0) {
                action = 4;
            }
            break;
        case 'q':
            if (strcmp(cmd_buf, "quit") == 0) {
                action = 5;
            }
            break;
        default:
            action = 0;
    }
    return action;
}

更优的扩展性方案:命令映射表

如果后续需要新增更多命令,switch版本仍需修改分支逻辑,而使用结构体映射表的方式可以让代码更简洁、扩展性更强,新增命令仅需在映射表中添加条目即可:

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

// 定义命令-动作映射结构体
typedef struct {
    const char *command;
    int action_code;
} CommandMap;

// 全局命令映射表,新增命令直接在这里添加
static const CommandMap cmd_mappings[] = {
    {"send", 1},
    {"list", 2},
    {"read", 3},
    {"del", 4},
    {"quit", 5}
};

// 计算映射表条目数量
static const int mapping_count = sizeof(cmd_mappings) / sizeof(cmd_mappings[0]);

// 自定义忽略大小写的字符串比较函数(跨平台兼容)
int strcasecmp_custom(const char *a, const char *b) {
    while (*a && *b) {
        int diff = tolower((unsigned char)*a) - tolower((unsigned char)*b);
        if (diff != 0) {
            return diff;
        }
        a++;
        b++;
    }
    return tolower((unsigned char)*a) - tolower((unsigned char)*b);
}

int getCommand(char *buffer) {
    for (int i = 0; i < mapping_count; i++) {
        if (strcasecmp_custom(buffer, cmd_mappings[i].command) == 0) {
            return cmd_mappings[i].action_code;
        }
    }
    // 未匹配到命令时返回0
    return 0;
}

注意事项

  1. 原代码仅判断字符串的前几个字符,比如输入send123会被误判为SEND命令,上述优化方案通过完整字符串匹配避免了这个问题;如果确实需要前缀匹配,可以将strcmp替换为strncmp并指定匹配长度。
  2. 跨平台开发时,注意系统内置的strcasecmp函数(Windows为_stricmp),使用自定义的strcasecmp_custom可以保证兼容性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 20:01:11