解析類 URL 參數格式字符串:cmd1=str1&cmd2=str2,其中 cmd 的個數和順序不固定。
& 分割出各 key=value 對= 分離鍵值switch-case 處理#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef enum {
CMD_UNKNOWN = -1,
CMD_1 = 1,
CMD_2 = 2
// 可擴展更多命令
} CmdType;
CmdType str_to_cmd(const char* key) {
if (strcmp(key, "cmd1") == 0) return CMD_1;
if (strcmp(key, "cmd2") == 0) return CMD_2;
return CMD_UNKNOWN;
}
void parse_cmd_string(const char* input) {
char* str = strdup(input); // 複製,因為 strtok 會修改原字符串
char* token = strtok(str, "&");
while (token != NULL) {
char* eq = strchr(token, '=');
if (eq) {
*eq = '\0'; // 分離 key 和 value
char* key = token;
char* value = eq + 1;
CmdType cmd = str_to_cmd(key);
switch (cmd) {
case CMD_1:
printf("處理 cmd1: %s\n", value);
break;
case CMD_2:
printf("處理 cmd2: %s\n", value);
break;
default:
printf("未知命令: %s=%s\n", key, value);
}
}
token = strtok(NULL, "&");
}
free(str);
}
int main() {
const char* test = "cmd1=hello&cmd2=world&cmd1=again";
parse_cmd_string(test);
return 0;
}
strtok 會修改原字符串,生產環境請用 strdup 複製strchr 查找首個 = 位置,支援 value 中包含 = 的情況輸入來自網絡/用戶時,務必檢查緩衝區長度,防止溢出。生產環境建議使用成熟庫(如 libcurl 的 URL 解析功能)。