首页 > 解决方案 > 在 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;
}

标签: cstringstrcmp

解决方案


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
        }
    }
}

推荐阅读