Wednesday, December 10, 2008

Replace all occurance of %20 with a blank space.

#define MAX_LEN 256

/*******************************************************
INPUT: 1) character string with one or more %20 patterns
2) length of the string
OUTPUT: 0 - SUCCESS
-1 - INVALID INPUT
-2 - No need to do anything.
Test Data: 1)"%20"
2)"This%20is"
3)"This%20is%20%20a"
4)"This%20is%20%20%20"
5)"This is a"
*******************************************************/
int FindPattern( TCHAR* szStr, size_t &len)
{
//Return Values
int iRet = -2;
//if invalid Input
if((szStr == NULL)||(len <= 0))
return -1;
if(len <3)
return iRet;

TCHAR *pAhead = szStr;
TCHAR *pBack = szStr;


//Loop till you reach the end of the string
while( *pAhead)
{

//if the pattern is found replace it with ' ' and reposition the pointers
if( (*pAhead == _T('%'))&& (*(pAhead+1) == _T('2'))&&
(*(pAhead+2) == _T('0')))
{
*pBack = _T(' ');
pAhead += 3;
pBack +=1;
iRet = 0;
}
else//copy the data and increment the pointer
{
*pBack++ = *pAhead++;
}
}
*pBack = 0;

len = _tcslen(szStr);
return iRet;
}
int _tmain(int argc, _TCHAR* argv[])
{
_TCHAR szPattern[MAX_LEN];
memset(szPattern,0,MAX_LEN);
_tcscpy_s(szPattern,MAX_LEN,_T("This is a beautiful world"));
size_t len = _tcslen(szPattern);
int retVal = FindPattern(szPattern, len);
if(retVal == 0)
{
_tprintf(_T("The \' \' replaced string for %%20 is %s"),szPattern);
}
else if(retVal == -2)
_tprintf(_T("The %s did not have any %%20 pattern"),szPattern);
else
_tprintf(_T("\nInvalid input\n"));
return retVal;
}

No comments: