Parse string and subtract a substring

I'm parsing a http header in C and need to subtract host name from the full url.

I managed to get the full url (http://www.example.com/hello.html) and the path name (hello.html) but couldn't subtract (full url - path name) host name (example.com).

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

Any help would be appreciated. Thanks

Answers


You can use memcpy, like this:

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);

Here is a demo on ideone.


Need Your Help

Upgrading Pyramid/SQLAlchemy web apps

python sqlalchemy pyramid paster sqlalchemy-migrate

I've got a standard run of the mill Pylons Pyramid application, that uses SQLAlchemy for its database persistence.