how to Trim the url in c++.
Hello,
I got stuck in trim the url to header host format in c++.
Here i have string or char * type url as below
<code>
http://www.cplusplus.com/user/
</code>
I want to reduce to
cplusplus.com
as my final string. i did it as much as i can but i thought it was not a proper way to trim.
Any help would be appreciated.
Last edited on
here i tried , but i don't think this is the best way to do this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
string str ("http://www.cplusplus.com/user/");
char *ptr ,*st = NULL;
ptr = strchr( (char *) str.c_str(), ':');
cout<< ptr <<endl; // :// ......
ptr++;
cout<< ptr << endl; // // .....
while (*ptr == '/') {
if(*(ptr+1) == '/') {
ptr = strchr( (char*) str.c_str(), '/');
cout<<ptr <<endl; // / ....
}
++ptr;
}
cout<< ptr << endl; // ......
|
Got it ..using string find with substr ..so easily
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
// http://ideone.com/4DkTyb
#include <iostream>
#include <regex>
#include <string>
std::string extract_authority(std::string uri)
{
// See: Apendix B from http://www.ietf.org/rfc/rfc2396.txt for regular expression
std::regex uri_exp(R"xxx(^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?)xxx");
std::smatch matches;
if (std::regex_match(uri, matches, uri_exp) && matches.size() >= 5)
return matches[4].str();
return std::string();
}
std::string trim_prefix(std::string s, std::string prefix)
{
return s.find(prefix) == 0 ? s.substr(prefix.length()) : s;
}
int main()
{
std::vector<std::string> examples =
{
R"(http://www.ics.uci.edu/pub/ietf/uri/#Related)",
R"(http://www.cplusplus.com/user/)",
R"(ftp://ftp.is.co.za/rfc/rfc1808.txt)",
R"(gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles")",
R"(http://www.math.uio.no/faq/compression-faq/part1.html)",
R"(mailto:mduerst@ifi.unizh.ch)",
R"(news:comp.infosystems.www.servers.unix")",
R"(telnet://melvyl.ucop.edu/)",
};
for (auto example : examples)
{
auto auth = extract_authority(example);
std::cout << '"' << trim_prefix(auth, "www.") << "\" (" << example << ")\n";
}
}
|
Topic archived. No new replies allowed.