【发布时间】:2019-04-28 12:58:34
【问题描述】:
我正在尝试找到在 C 中比较多个字符串的最佳方法。
目前,我正在使用strcmp(); 函数,但结果是太多了if
陈述。我也在使用三元运算符,但不幸的是,它没有帮助。
有没有更好的解决方案?
这是示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char command[] = "First Second Third";
char * del = " ";
char * token;
char * strings[3];
int n = 0;
token = strtok(command, del);
while (token != NULL){
strings[n] = token;
token = strtok(NULL, del);
n++;
}
// Now, strings[0] = "First", strings[1] = "Second", and strings[2] = "Third"
// Only examine strings[1] and strings[2] after we know strings[0] = "First".
if (strcmp("First", strings[0]) == 0){
//do something
if (strcmp("Second", strings[1]) == 0){
//do something
if (strcmp("Third", strings[2]) == 0){
//do something
printf("CORRECT");
//do something
}
}
}
return 0;
}
【问题讨论】:
-
向我们展示您的代码。
-
请通过展示您的实际问题或您想要优化的具体案例的代码来集中您的问题。
-
有时您只需要输入大量代码 - 不要寻找掩盖您正在尝试做的事情的技巧
-
这听起来像是一个 X/Y 问题 - 为什么你想匹配多个字符串?你想通过匹配多个字符串来完成什么?您正在尝试做什么的高级描述是什么?