1

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!

7
  • How do you define a comparison between a string and an array of strings? Commented Sep 14, 2013 at 21:58
  • How large is the array of strings? The solution would be different for 100k strings than for 5 strings. @H2CO3, I believe he means in. Commented Sep 14, 2013 at 21:58
  • @MattBryant Um, then a linear search for an array of size 4. Perhaps. Commented Sep 14, 2013 at 22:00
  • Definitely. But if he has a large array then he should probably look into binary search then strncmp. Or he could use tries. Or any number of cool things. Commented Sep 14, 2013 at 22:01
  • @Mr.Student No. @Gangadhar I don't have any relevant code to post. I just have the array const char* cmds[] = {"wait", "pwd", "cd", "exit"}; and my program needs to compare a string the user inputs (the first word is stored in a variable) to see if it matches any of the elements in cmd. Commented Sep 14, 2013 at 22:03

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.