Is there something like startsWith(str_a, str_b)
in the standard C library?
It should take pointers to two strings that end with nullbytes, and tell me whether the first one also appears completely at the beginning of the second one.
Examples:
"abc", "abcdef" -> true
"abcdef", "abc" -> false
"abd", "abdcef" -> true
"abc", "abc" -> true
There's no standard function for this, but you can define
bool prefix(const char *pre, const char *str)
{
return strncmp(pre, str, strlen(pre)) == 0;
}
We don't have to worry about str
being shorter than pre
because according to the C standard (7.21.4.4/2):
The
strncmp
function compares not more thann
characters (characters that follow a null character are not compared) from the array pointed to bys1
to the array pointed to bys2
."