Hemant Bhargava
Hemant Bhargava

Reputation: 3585

Comparing many const char* with one const char*

Might be basic one today.

I have an input as a const char* and I want to compare it with the many options of const char*. Something like I have written below.

str_equal - Think of it as a compare function for const char*. 'str' is the input const char*.

So, written like this:

bool function1(const char* str) {
  if (str_equal(str, "abc")) {
    // Do for abc
  } else if (str_equal(str, "def")) {
    // Do for def
  } else if (str_equal(str, "ghi")) {
    // Do for ghi
  } ...
  ...
}

Wondering what are the other possible ways to achieve this. As you can see, it looks very ugly.

Upvotes: 2

Views: 179

Answers (2)

Serge
Serge

Reputation: 12364

depends on your needs there are several other way you can use.

For example, you an initially create a sorted array of strings which you compare against and use binary search: https://linux.die.net/man/3/bsearch.

You can use hash tables or trees as well, just a bit more complicated.

In some cases you might even create a combined string of all your strings like "abcdefdhi" and use strstr to find the string in a singe operation.

Upvotes: 1

unwind
unwind

Reputation: 399979

I would use an array of structures:

static bool do_abc(void)
{
  // ...
}

bool dispatch(const char *str)
{
  static const struct {
    const char *key;
    bool (*func)(void);
  } funcs[] = {
    { "abc", do_abc },
    { "def", do_def },
    { "ghi", do_ghi },
  };
  for (size_t i = 0; i < sizeof funcs / sizeof *funcs; ++i)
  {
    if(strcmp(funcs[i].text, str) == 0)
      return funcs[i].func();
  }
  return false;
}

This assumes that all the functions have the same signature, otherwise it's hard to generalize.

By the way, this can be called an example of "data-driven code", which is often nice.

Upvotes: 5

Related Questions