FroyoJones
FroyoJones

Reputation: 41

Searching a char* for a member of char* array in c

I've been a little stuck on searching through strings to find if a member of an array exists in them.

For example, I am trying to find where one of these operators: char* Operators[2] = {"+", "-"};

Would be in this string string check = "this+that";

Upvotes: 0

Views: 540

Answers (1)

David C. Rankin
David C. Rankin

Reputation: 84579

Whenever you need to check for a substring within a string, you want the strstr() function from string.h. The declaration is:

char *strstr(const char *haystack, const char *needle);

Where haystack is the full string (check in your case) and needle is the substring you want to find (the elements of Operators in your case). Since you have multiple substrings to test for, you will need to loop over each substring calling strstr() with each to check if that operator is found in check. You can do that simply with:

#include <stdio.h>
#include <string.h>

int main (void) {
    
    char *check = "this+that";                              /* pointer to string literal */
    char *Operators[] = {"+", "-"};                         /* array of pointers */
    size_t nstrings = sizeof Operators/sizeof *Operators;   /* no. of elements */
    
    for (size_t i = 0; i < nstrings; i++) {                 /* loop over each Operators */
        char *p = strstr (check, Operators[i]);             /* is it substring of check? */
        if (p != NULL)                                      /* if substring found */
            printf ("Operators[%zu] %c in check\n", i, *p); /* output result */
    }
}

Example Output

$ ./bin/operators
Operators[0] + in check

Upvotes: 1

Related Questions