Interview Questions

Write a function which finds a substring in a string

Software QA/Tests Interview Questions from Microsoft


(Continued from previous question...)

Write a function which finds a substring in a string

Question:
Software Engineer in Test:
Write a function which finds a substring in a string and replaces all such occurances with another string. Prototype of the function :
char* FindReplace(char* src, char* find, char* replace);



maybe an answer:


#include<iostream.h>
#include<string.h>

char* findReplace(char* src, char* find, char* replace)
{
int s,f,r,len,i,j,k,x,y;
char z[20];

s=strlen(src);
f=strlen(find);
r=strlen(replace);

i=0;

while(i<s)
{
for(j=i,k=0;k<f;k++,j++)
{
if(src[j]!=find[k])// comparing substring in src and 'find', character by character
break;
}

if(k!=f)//If substring doesn't match with 'find', increment i to start comparing from the next character.
{
i++;
}

else// substring and find matched
{
if(r==f)// case 1: find and replace of same length
{
for(x=i,y=0;x<i+f;x++,y++)
{
src[x]=replace[y];
}
i=--x;// to start comparing starting from the character following the 'find' substring in src

}
else if(r<f)// case 2: find longer than replace
{
for(y=0;y<r;i++,y++)
{
src[i]=replace[y];
}

for(x=i,y=i+f-r;y<s;x++,y++)
src[x]=src[y];

src[x]='\0';
}

else// case 3: replace longer than find
{
strcpy(z,src);
for(x=i+r,y=i+f;y<s;x++,y++)
{
src[x]=z[y];
}
src[x]='\0';

for(y=0;y src[i]=replace[y];

s+=r-f;
}
}
}
return src;
}

int main()
{
char src[50],find[50],replace[50],*final;
char* findReplace(char*, char*,char*);

cout<<"\n Enter source ";
gets(src);

cout<<"\n Enter find ";
gets(find);

cout<<"\n Enter replace : ";
gets(replace);

final=findReplace(src,find,replace);
cout<<"\n "<<final;

return 0;
}

(Continued on next question...)

Other Interview Questions