Comparing a single string to an array of strings in C

≯℡__Kan透↙ 提交于 2019-12-11 07:54:03

问题


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?

Example:

comparing the string "pwd" to an array containging {"wait", "pwd", "cd", "exit"}

Thanks in advance for your help!


回答1:


I would do something like the following:

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

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.



来源:https://stackoverflow.com/questions/18806788/comparing-a-single-string-to-an-array-of-strings-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!