Ad

How To Check If A String Is Subset Of Another String In C

- 1 answer

I want to create a function that checks if an array is derived from elements of another array in C. Here is my code. I don't know why it isn't working.

int allDelimiter(char str[81], char delimiters[])
{
    int k = 0;

    char* pch = strstr(str, delimiters);

    if (pch)
    {
        k++;
    }
    return k;
}

int main()
{
    char string[81] = { ",?',,," };
    
    char delim[] = ", ? ! ''";
    int j = 0;

    j = allDelimiter(string, delim);

    if (j > 0)
    {
        puts("ALL DELIMITERS");
    }
    else
    {
        puts("NOT ALL DELIMITERS");
    }
    return 0;
}

I want the output to be ALL DELIMITERS i.e all elements of str[] are elements of delim[].

Ad

Answer

If I understand the question

//returns zero if yes
int containsAll(const char *str, const char *charlist)
{
    int result = 0;
    while(*str)
    {
        if(!strchr(charlist, *str++))
        {
            result = -1;
            break;
        }
    }
    return result;
}

int main()
{
    char string[81] = { ",?',,," };
    
    char delim[] = ", ? ! ''";

    if (!containsAll(string, delim))
    {
        puts("ALL DELIMITERS");
    }
    else
    {
        puts("NOT ALL DELIMITERS");
    }
    return 0;
}
Ad
source: stackoverflow.com
Ad