Thursday, June 23, 2011

Wap to Replace all the instances of ’%’ with this string s,offered that the length of the array

Given an array of dimension n with very first l positions crammed with characters and a string s ,replace all the instances of ’%’ with this string s,offered that the length of the array is enough to deal with these substitutions.

input output

eg: abcdef%ghi%—— and “ppp” abcdefpppghippp



Although program is Simple but i am posting here as i found on one forum that it is asked by MS:)

Data Structure:Array

Algorithm:
1.count number of % character
2.increase size of array by lenth + 2* number op & chars.
3. scan through new array & replace all % occurance with "ppp"


class test
{
public static void ReplaceFun(char[] str, int length) {
int percentCount= 0, newLength, i = 0;
for (i = 0; i < length; i++)
{
         if (str[i] == '%')
        {
            percentCount++;
        }
}

newLength = length + percentCount* 2; str[newLength] = '\0';

for (i = length - 1; i >= 0; i--)
{
if (str[i] == '%')
{
str[newLength - 1] = 'p';
str[newLength - 2] = 'p';
str[newLength - 3] = 'p';
newLength = newLength - 3;
}
else
{
str[newLength - 1] = str[i];
newLength = newLength - 1;
}

}
System.out.println(str);
}
public static void main(String a[])
{
ReplaceFun(new char[]{'s','h','%','a','%','%','s','h','a','n','%','%','%','k'},15);

}
}

2 comments :

Sa said...

length + percentCount* 3; is not correct, it should be length +percentCount*2, there are only two extra characters.

Unknown said...

@sa .thnx for correction i have updated the post :)