I'm testing if a URL contains certain extensions. I have to do this about 100M times. I'm trying to pass the URL without the query string so I can compare the last 3 chars from the URL against some conditions.
My question is, can I pass only http://www.e.com/msusa/DisplayContactPage.jsp to textExtension? without modifying url in main and without strdup the string?
int testExtension(char *url) {
// compare last 3 chars against possible extensions
// return 0 if matches extension, else return 1
return match ? 0 : 1;
}
int main () {
char *url = "http://www.e.com/msusa/DisplayContactPage.jsp?q=string&t=12"
testExtension(url);
}
I can certainly do:
if ((end=strchr(url, '?')))
*end=0;
but that modifies url
Steps you can take:
Find the '?' in the URL.
char* cp = strchr(url, '?');
If you find it, move the pointer back by three. If you don't find it, move it to 3 characters before the end of the string.
Check that the previous character is a '.'.That is the start of the extension. Pass the pointer to textExtension.
if ( cp == NULL )
{
len = strlen(url);
cp = url + (len-3);
}
cp -= 3;
if ( *(cp-1) != '.' )
{
// Deal with the condition.
}
// Call textExtension.
testExtension(cp);
Make sure you don't access anything beyond the '?' or the null character in testExtension.
If you are not sure about the number of characters in the extension, you can use:
char* cp = strchr(url, '?');
if ( cp == NULL )
{
len = strlen(url);
cp = url + len;
}
// Move the pointer back until you find the '.'
while ( *cp != '.' && cp > url )
{
--cp;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With