c - 如何从 C 中的 char 数组中去除前导 "http://"?

标签 c string

我有一个传递 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/

相关文章:

c++ - 从字符串中删除特定的子字符串

c - 添加多维数组中每个元素的数字

c - 程序的 CPU 使用率突然飙升,看起来像是暂停了

c++ - 为什么 "\?"在 C/C++ 中是一个转义序列?

PHP 回显不起作用

javascript - 正则表达式匹配 3 个条件?

python - 在python中获取url的特定部分

c++ - 在 C 中使用无效指针值是否合法?

c - 三星DDR4 : How read/write on mode register?

c - 在 C 中打印新行之前是否可以等待几秒钟?