c - 在 C 中比较多个字符串的最佳方法是什么?
问题描述
我试图找到在 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;
}
解决方案
OP的代码有一些问题
while (token != NULL)
没有限制为 3 个循环。代码可能会尝试strings[3] = token;
// while (token != NULL){ while (n < 3 && token != NULL){
代码使用
strings[0]
,strings[1]
,strings[2]
而不首先确保解析了许多标记。// strcmp("First", strings[0]) == 0 (n > 0 && strcmp("First", strings[0]) == 0)
代码保存指向原始字符串的指针。一旦
strtok()
再次调用,先前的令牌可能会丢失/更改。
“最佳”方式涉及对密钥和目标进行散列处理,但这里需要解释很多。
替代方案:在 OP 的示例中需要这样一个简单的匹配,代码可以"%n"
用来记录扫描的偏移量。
int n1 = 0, n2 = 0, n3 = 0;
sscanf(command, "First %n Second %n Third %n", &n1, &n2, &n3);
if (n1) { // n1 is non-zero if scan matched "First"
//do something
if (n2) { // n2 is non-zero if scan matched "First Second"
//do something
if (n3) {
//do something
printf("CORRECT");
//do something
}
}
}
推荐阅读
- android - 引发自定义异常时的 InvocationTargetException
- python-3.x - 如何在数据框中找到与另一个属性的多个值相关联的属性?
- git - 詹金斯管道的 GIT 交叉签出和依赖项检查
- c++ - 如果没有重新散列,为什么 unordered_set::begin() 会改变?
- react-native - 错误:EPERM:不允许操作,重命名
- html - 如何将我的元素放在代码生成器的正确位置
- flask - 有条件地调用 wtforms 验证
- html - 使用顶部位置会影响整个页面
- r - 按组在多个时间间隔列之间重叠
- angular - TypeError: _co.registerNow 不是函数