top of page
Search
Writer's pictureAbhinaw Tripathi

Write a method to replace all spaces with %20 in a String.(Note-Perform in place operation only.)


public void replaceSpaces(Char[] str, int length)

{

int spaceCount=0;

int newLength,i;

for(i=0;i<lenght;i++)

{

if(str[i] == ' ')

{

spaceCount++;

}

}

newLenght =newLength + spaceCount *2;

str[newLength] = '\0' ;

for( i=length -1; i>=0,i--)

{

if(str[i] == ' ')

{

str[newLength -1] = '0';

str[newLength -2] = '2';

str[newLength -3] = '%';

newLength =newLength - 3 ;

}

else

{

str[newLength -1] = str[i] ;

newLength =newLength - 1;

}

}

}

Note: i have implemented this problem using character arrays because java string are immutable.if you will use string directly.this would require a new copy of the string but it would allow us to implement this in just one pass.

6 views0 comments

Recent Posts

See All
bottom of page