解析字符串并减去一个子字符串
我解析了C中的一个http头并且需要从完整的url中减去主机名。解析字符串并减去一个子字符串
我设法得到完整的网址(http://www.example.com/hello.html)和路径名(hello.html),但不能减去(完整的URL - 路径名)主机名(example.com)。
Example full url: http://www.example.com/hello.html - DONE
host name: example.com - TODO
path name: /hello.html - DONE
任何帮助,将不胜感激。由于
您可以使用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。
我在malloc行中收到一条错误消息,提示“void *'无效转换为'char *'”。 – chatu 2013-05-02 16:47:42
我必须在malloc之前施放(char *)。谢谢@dasblinkenlight。 – chatu 2013-05-02 16:56:25
@chatu此错误表示您正在使用C++编译器进行编译:符合标准的C编译器不需要此转换。 – dasblinkenlight 2013-05-02 17:05:33
你可以做这样的事情
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);
只是用'strncpy' – 2013-05-02 16:30:59
你读在C http头,不知道处理字符串?在问之前你应该在网上搜索。 – erencan 2013-05-02 16:34:52