Skip to content

Instantly share code, notes, and snippets.

@litefeel
Last active January 19, 2024 16:50
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save litefeel/1197e5c24eb9ec93d771 to your computer and use it in GitHub Desktop.
Save litefeel/1197e5c24eb9ec93d771 to your computer and use it in GitHub Desktop.
c++ urlencode
// http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/package.html#encodeURIComponent()
void hexchar(unsigned char c, unsigned char &hex1, unsigned char &hex2)
{
hex1 = c / 16;
hex2 = c % 16;
hex1 += hex1 <= 9 ? '0' : 'a' - 10;
hex2 += hex2 <= 9 ? '0' : 'a' - 10;
}
string urlencode(string s)
{
const char *str = s.c_str();
vector<char> v(s.size());
v.clear();
for (size_t i = 0, l = s.size(); i < l; i++)
{
char c = str[i];
if ((c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
c == '-' || c == '_' || c == '.' || c == '!' || c == '~' ||
c == '*' || c == '\'' || c == '(' || c == ')')
{
v.push_back(c);
}
else if (c == ' ')
{
v.push_back('+');
}
else
{
v.push_back('%');
unsigned char d1, d2;
hexchar(c, d1, d2);
v.push_back(d1);
v.push_back(d2);
}
}
return string(v.cbegin(), v.cend());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment