我有一个传递 URL 的函数(在 C 中)。此函数仅在 URL 参数为 www.example.com
形式时有效,当为 http://www.example.com
时无效。
我想修改此函数,以便在以 http://www.example.com
形式传递 URL 时,它会去除前导 http://
(如果存在),以便它能够正确运行。
我如何在 C 中执行此操作?
这是有问题的功能(让我知道是否有更好的方法来做到这一点):
char* get_ip (char* url)
{
struct hostent* h;
if ((h = gethostbyname(url)) == NULL)
return NULL;
return inet_ntoa(*((struct in_addr*)h->h_addr));
}
最佳答案
总是有简单的方法:
char *url;
// ...
const char *http = "http://";
if (!strncmp(url, http, strlen(http)))
url += strlen(http);
或者,如果您想摆脱一般形式的协议(protocol)说明符(例如 https):
char *url;
char *p = strstr(url, "://");
if (p)
url = p + 3; // skip past :// part of URL
关于c - 如何从 C 中的 char 数组中去除前导 "http://"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7968774/