![]() |
General Programming »
String handling »
Text Conversion
Beginner
URLEncodeBy Ryszard KrakowiakConvert string using URLEncode method |
VC6Win2K, MFC, Dev
|
|
Advanced Search |
|
|
|
||||||||||||||||
I use this functions to prepare POST strings with XML data. The first function URLEncode1 uses less memory but is slower than the second URLEncode2. Both functions return a CString and get a CString as the input parameter.
The demo project contains sample usage with execution time of presented functions.
inline BYTE toHex(const BYTE &x) { return x > 9 ? x + 55: x + 48; }
CString URLEncode1(CString sIn)
{
CString sOut;
int k;
const int nLen = sIn.GetLength() + 1;
register LPBYTE pOutTmp = NULL;
LPBYTE pOutBuf = NULL;
register LPBYTE pInTmp = NULL;
LPBYTE pInBuf =(LPBYTE)sIn.GetBuffer(nLen);
BYTE b = 0;
//count not alphanumeric characters
k = 0;
pInTmp = pInBuf;
while(*pInTmp)
{
if (!isalnum(*pInTmp) && !isalnum(*pInTmp))
k++;
pInTmp++;
}
//alloc out buffer
pOutBuf = (LPBYTE)sOut.GetBuffer(nLen + 2 * k); //new BYTE [nLen + 3 * k];
if(pOutBuf)
{
pInTmp = pInBuf;
pOutTmp = pOutBuf;
// do encoding
while (*pInTmp)
{
if(isalnum(*pInTmp))
*pOutTmp++ = *pInTmp;
else
if(isspace(*pInTmp))
*pOutTmp++ = '+';
else
{
*pOutTmp++ = '%';
*pOutTmp++ = toHex(*pInTmp>>4);
*pOutTmp++ = toHex(*pInTmp%16);
}
pInTmp++;
}
*pOutTmp = '\0';
//sOut=pOutBuf;
//delete [] pOutBuf;
sOut.ReleaseBuffer();
}
sIn.ReleaseBuffer();
return sOut;
}
CString URLEncode2(CString sIn)
{
CString sOut;
const int nLen = sIn.GetLength() + 1;
register LPBYTE pOutTmp = NULL;
LPBYTE pOutBuf = NULL;
register LPBYTE pInTmp = NULL;
LPBYTE pInBuf =(LPBYTE)sIn.GetBuffer(nLen);
BYTE b = 0;
//alloc out buffer
pOutBuf = (LPBYTE)sOut.GetBuffer(nLen * 3 - 2);//new BYTE [nLen * 3];
if(pOutBuf)
{
pInTmp = pInBuf;
pOutTmp = pOutBuf;
// do encoding
while (*pInTmp)
{
if(isalnum(*pInTmp))
*pOutTmp++ = *pInTmp;
else
if(isspace(*pInTmp))
*pOutTmp++ = '+';
else
{
*pOutTmp++ = '%';
*pOutTmp++ = toHex(*pInTmp>>4);
*pOutTmp++ = toHex(*pInTmp%16);
}
pInTmp++;
}
*pOutTmp = '\0';
//sOut=pOutBuf;
//delete [] pOutBuf;
sOut.ReleaseBuffer();
}
sIn.ReleaseBuffer();
return sOut;
}
26.06.2001 - changed out buffer memory allocation (thx 2 Marc Brooks and Matthias)
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 25 Jun 2001 Editor: James Spibey |
Copyright 2001 by Ryszard Krakowiak Everything else Copyright © CodeProject, 1999-2009 Web12 | Advertise on the Code Project |