replacing spaces with %20 in c program
I have written the following program to replace spaces with %20.It works
fine. But it prints some garbage values for the pointer variable ptr
though it might have been limited to 8 characters as the malloc assigns it
8 bytes of memory.
Can anyone tell me where did I go wrong here ? Or is there any in place
algorithm ?
void replaceSpaces(char *inputStr )
{
char *ptr;
int i,length, spaceCount=0;
int newLength,j;
for (length=0; *(inputStr+length)!='\0';length++ )
{
if (*(inputStr+length)==' ')
{
spaceCount++;
}
}
newLength = length + 2*spaceCount;
ptr = (char *)malloc(newLength*sizeof(char));
for ( i = length-1; i >=0; i--)
{
if (*(inputStr+i)==' ')
{
*(ptr+newLength-1)='0';
*(ptr+ newLength-2)='2';
*(ptr+newLength-3)='%';
newLength = newLength -3;
}
else
{
*(ptr+newLength-1) = *(inputStr+i);
newLength = newLength -1;
}
}
for ( i = 0; *(ptr+i)!='\0'; i++)
{
printf("%c",*(ptr+i));
}
}
No comments:
Post a Comment