URL-decode

 
#ifndef PJ_String_URL_Decode
#define PJ_String_URL_Decode
#include <cctype> // isxdigit()
#include <string>
///
/// The URLDecode function below decodes an URL-encoded string and
/// returns the decoded string.
///
/// Dedicated to the public domain.
///
/// @author: Peter Jansson (http://peter.jansson.net/)
///
/// Help-function:
/// Convert a hex char from base 16 to base 10 (strtol could be used).
int hex2dec(const char& hex)
{
   return ((hex>='0'&&hex<='9')?(hex-'0'):(std::toupper(hex)-'A'+10));
}
std::string
URLDecode(
      const std::string& URLin)
{
   std::string URLout;
   // We will shrink somewhat but the input is a good estimate.
   URLout.reserve(URLin.size());
   const char* in(URLin.c_str()); // '\0' appended at the end.
   for(;*in;in++) // End the loop if we encounter '\0'.
   {
      // Done if we find \0 (not a hexdigit), at in[1] or in[2].
      if(*in!='%'||!std::isxdigit(in[1])||!std::isxdigit(in[2]))
      {
         if(*in=='+')
            URLout+=' ';
         else
            URLout+=*in;
      }
      else // Convert all %xy hex codes into ASCII characters.
      {
         // The if(...) above will ensure that we do not have three consecutive \0.
         if( (in[1]=='2' && in[2]=='6')
               || (in[1]=='3' && (in[2]=='d'||in[2]=='D')))
         { // Do not alter URL delimeters.
            URLout+='%';
            URLout+=in[1];
            URLout+=in[2];
         }
         else
            URLout+=static_cast<char>(hex2dec(in[1])*16+hex2dec(in[2]));
         // It is safe to increment by two since we have three non-\0 characters.
         in+=2;
      }
   }
   return URLout;
}
#endif
 

Inlägg (RSS) och Kommentarer (RSS).

 


Advertisements:
Cheap Gas - Loans - Mortgage - Loans