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!

IrateIrish
  • 219
  • 2
  • 6
  • 12
  • How do you define a comparison between a string and an array of strings? –  Sep 14 '13 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`. – Matt Bryant Sep 14 '13 at 21:58
  • @MattBryant Um, then a linear search for an array of size 4. Perhaps. –  Sep 14 '13 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. – Matt Bryant Sep 14 '13 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`. – IrateIrish Sep 14 '13 at 22:03
  • @flexcalibur6 please try something.take string input, rotate loop on each iteration compare input with the command. if found do what ever you want . try to make some code for this .if still you get any issue then post your code.asking like this is not correct on SO. – Gangadhar Sep 14 '13 at 22:07
  • You could try a simple for loop and iterate through each string, while using strncmp.Though technically that would mean both strings that are being compared ought to be const char * – Dr.Knowitall Sep 14 '13 at 22:08

1 Answers1

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.

Matt Bryant
  • 4,841
  • 4
  • 31
  • 46