It’s not immediately obvious how to check if a string is a valid prefix of another in C, given the lack of high-level string manipulation tools. Below explains how this can be done.

Checking the prefix

For this function we’ll use strncmp which accepts two strings and the maximum number of characters to compare, and returns an int. If the return value is equal to 0, the strings are equal. We can leverage this by checking the size of the prefix string, and calling strncmp using that size. See the code below.

int prefix(char *pre, char *str)
{
    return strncmp(pre, str, strlen(pre)) == 0;
}

My function, prefix, takes two strings as arguments and returns 1 if the pre string is a valid prefix of str. You can modify this to suit your needs, but the basic premise is quite simple.