解析字符串并减去子字符串

时间:2013-05-02 16:29:41

标签: c string

我正在解析C中的http标头,需要从完整的URL中减去主机名。

我设法获取完整网址(http://www.example.com/hello.html)和路径名称(hello.html),但无法减去(完整网址 - 路径名)主机名(example.com)。

Example full url: http://www.example.com/hello.html - DONE
host name: example.com - TODO
path name: /hello.html - DONE

任何帮助将不胜感激。感谢

2 个答案:

答案 0 :(得分:3)

您可以使用memcpy,如下所示:

char *url = "http://www.example.com/hello.html";
// find the last index of `/`
char *path = url + strlen(url);
while (path != url && *path != '/') {
   path--;
}
// Calculate the length of the host name
int hostLen = path-url;
// Allocate an extra byte for null terminator
char *hostName = malloc(hostLen+1);
// Copy the string into the newly allocated buffer
memcpy(hostName, url, hostLen);
// Null-terminate the copied string
hostName[hostLen] = '\0';
...
// Don't forget to free malloc-ed memory
free(hostName);

这是demo on ideone

答案 1 :(得分:0)

您可以执行类似

的操作
char Org="http://www.example.com/hello.html";
char New[200];
char Path="/hello.html";
memcpy(New,Org,strlen(Org)-strlen(Path));
New[strlen(Org)+strlen(Path)]=0;
printf("%s\n",New+12);