Created
September 25, 2018 16:08
-
-
Save kevinkreiser/3d06d6ce3522bb675e4d2fac75421e76 to your computer and use it in GitHub Desktop.
simple header only url decoder
This file contains 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
#ifndef TEST_DECODE | |
#pragma once | |
#else | |
#include <iostream> | |
#endif | |
#include <string> | |
std::string urldecode(const std::string& url) { | |
// make a place for the output | |
std::string decoded; | |
decoded.reserve(url.size()); | |
// keep going until we cant go anymore | |
size_t pos = 0; | |
while (pos < url.size()) { | |
// if we can find a percent in the remaining string | |
auto next_pos = url.find('%', pos); | |
if (next_pos < url.size() - 2) { | |
// copy everything up to that point | |
decoded.append(url, pos, next_pos - pos); | |
// decode it | |
auto c = | |
static_cast<std::string::value_type>(std::stoi(url.substr(next_pos + 1, 2), nullptr, 16)); | |
decoded.push_back(c); | |
// move pos past the end of what we decoded | |
pos = next_pos + 3; | |
} // we were done so just get the rest | |
else { | |
decoded.append(url, pos, url.size() - pos); | |
pos = url.size(); | |
} | |
} | |
// hand it back | |
return decoded; | |
} | |
#ifdef TEST_DECODE | |
int main(int argc, char** argv) { | |
std::cout << urldecode(argv[1]) << std::endl; | |
return 0; | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment