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):
Answer from Fred Foo on Stack OverflowThe
strncmpfunction compares not more thanncharacters (characters that follow a null character are not compared) from the array pointed to bys1to the array pointed to bys2."
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
strncmpfunction compares not more thanncharacters (characters that follow a null character are not compared) from the array pointed to bys1to the array pointed to bys2."
Apparently there's no standard C function for this. So:
bool startsWith(const char *pre, const char *str)
{
size_t lenpre = strlen(pre),
lenstr = strlen(str);
return lenstr < lenpre ? false : memcmp(pre, str, lenpre) == 0;
}
Note that the above is nice and clear, but if you're doing it in a tight loop or working with very large strings, it does not offer the best performance, as it scans the full length of both strings up front (strlen). Solutions like wj32's or Christoph's may offer better performance (although this comment about vectorization is beyond my ken of C). Also note Fred Foo's solution which avoids strlen on str (he's right, it's unnecessary if you use strncmp instead of memcmp). Only matters for (very) large strings or repeated use in tight loops, but when it matters, it matters.
bool StartsWith(const char *a, const char *b)
{
if(strncmp(a, b, strlen(b)) == 0) return 1;
return 0;
}
...
if(StartsWith("http://stackoverflow.com", "http://")) {
// do something
}else {
// do something else
}
You also need #include<stdbool.h> or just replace bool with int
I would suggest this:
char *checker = NULL;
checker = strstr(usUrl, "http://");
if(checker == usUrl)
{
//you found the match
}
This would match only when string starts with 'http://' and not something like 'XXXhttp://'
You can also use strcasestr if that is available on you platform.