我正在测试 URL 是否包含某些扩展名。我必须这样做大约 100M 次。我试图传递不带查询字符串的 URL,以便我可以将 URL 的最后 3 个字符与某些条件进行比较。
我的问题是,我可以只将 http://www.e.com/msusa/DisplayContactPage.jsp
传递给 textExtension
吗?不修改 main 中的 url
并且没有 strdup
字符串?
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);
}
我当然可以:
if ((end=strchr(url, '?')))
*end=0;
但这会修改 url
最佳答案
您可以采取的步骤:
在 URL 中找到
'?'
。char* cp = strchr(url, '?');
如果找到它,将指针向后移动三。如果没找到,就把它移到字符串末尾前3个字符。
检查前一个字符是否为
'.'
。这是扩展的开始。将指针传递给textExtension
。if ( cp == NULL ) { len = strlen(url); cp = url + (len-3); } cp -= 3; if ( *(cp-1) != '.' ) { // Deal with the condition. } // Call textExtension. testExtension(cp);
确保您不会访问
'?'
或testExtension
中的空字符以外的任何内容。
如果您不确定扩展名中的字符数,您可以使用:
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;
}
关于c - 将字符串中的 n 个字符传递给 C 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32322947/