Created
March 30, 2017 11:34
-
-
Save RedCarrottt/c7a056695e6951415a0368a87ad1e493 to your computer and use it in GitHub Desktop.
URI Parser in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Original code: http://stackoverflow.com/questions/2616011/easy-way-to-parse-a-url-in-c-cross-platform */ | |
#include <string> | |
struct url { | |
public: | |
url(const std::string& url_s) { | |
this->parse(url_s); | |
} | |
std::string protocol_, host_, path_, query_; | |
private: | |
void parse(const std::string& url_s); | |
}; | |
#include <string> | |
#include <algorithm> | |
#include <cctype> | |
#include <functional> | |
#include <iostream> | |
using namespace std; | |
// ctors, copy, equality, ... | |
void url::parse(const string& url_s) | |
{ | |
const string prot_end("://"); | |
string::const_iterator prot_i = search(url_s.begin(), url_s.end(), | |
prot_end.begin(), prot_end.end()); | |
protocol_.reserve(distance(url_s.begin(), prot_i)); | |
transform(url_s.begin(), prot_i, | |
back_inserter(protocol_), | |
ptr_fun<int,int>(tolower)); // protocol is icase | |
if( prot_i == url_s.end() ) | |
return; | |
advance(prot_i, prot_end.length()); | |
string::const_iterator path_i = find(prot_i, url_s.end(), '/'); | |
host_.reserve(distance(prot_i, path_i)); | |
transform(prot_i, path_i, | |
back_inserter(host_), | |
ptr_fun<int,int>(tolower)); // host is icase | |
string::const_iterator query_i = find(path_i, url_s.end(), '?'); | |
path_.assign(path_i, query_i); | |
if( query_i != url_s.end() ) | |
++query_i; | |
query_.assign(query_i, url_s.end()); | |
} | |
int main() { | |
url u("https://github.com/redcarrottt?query=1"); | |
cout << u.protocol_ << '\n' | |
<< u.host_ << '\n' | |
<< u.path_ << '\n' | |
<< u.query_ << '\n'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment