Ad

Filter Strings Using * (expand Operator) In C

- 1 answer

I have an array of different strings in C, like for example:

char *words[8] = {"hi", "cheesecake", "yellow", "happy", "cupcake", "red", "car", "chocolate cake"};

I want to filter them using a function like char *cakes[3] = filterWords(&words, "*cake*"); where the * represents anything at all. Is there a library for Linux that I could include to do that? If not, what would be the fastest way to implement this? (I have some idea of how to implement this, but it would probably be super inefficient).

Ad

Answer

I would use the fnmatch function for that. It is POSIX function so it is available under Linux and relatively easy to use: https://man7.org/linux/man-pages/man3/fnmatch.3.html Just beware that it handles other globbing patterns, like ?, so if your pattern is coming from the outside then you might need to handle those characters specially.

Here's an example, you might need some more work with it to have the exact function you need:

#include <fnmatch.h>
#include <stdio.h>

int main() {
  char *words[8] = {"hi", "cheesecake", "yellow", "happy", "cupcake", "red", "car", "chocolate cake"};
  const char *pattern = "*cake*";
  int i;

  for(i = 0; i < sizeof(words)/sizeof(words[0]); i++) {
    if (fnmatch(pattern, words[i], 0) == 0) {
      printf("Match: %s\n", words[i]);
    }
  }

  return 0;
}
Ad
source: stackoverflow.com
Ad