将单个字符串与C中的字符串数组进行比较 [英] Comparing a single string to an array of strings in C

查看:308
本文介绍了将单个字符串与C中的字符串数组进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序正在接受用户输入,然后接受输入的第一个单词并将其与接受的命令数组进行比较.将输入的第一个单词(在被标记化之后)与字符串数组进行比较的最佳方法是什么?

My program is accepting user input and then taking the first word inputted and comparing it to an array of accepted commands. What would be the best way to compare the first word inputted (after it has been tokenized) to an array of strings?

示例:

将字符串"pwd"与包含{"wait", "pwd", "cd", "exit"}

提前感谢您的帮助!

推荐答案

我将执行以下操作:

int string_in(const char* string, const char** strings, size_t strings_num) {
    for (size_t i = 0; i < strings_num; i++) {
        if (!strcmp(string, strings[i])) {
            return i;
        }
    }
    return -1;
}

检查数组中的每个字符串,如果相同,则返回索引.如果找不到,返回-1.
注意:容易受到溢出等的影响,请在尝试使用此代码之前对其进行修复.这会让您知道该怎么做,但不是好的代码.

Check each string in the array, if it's the same return the index. Return -1 if not found.
Note: Vulnerable to overflows, etc, fix them before trying to use this code. This will give you an idea of what to do, but is not good code.

这篇关于将单个字符串与C中的字符串数组进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆