Megasoft Interview Question
Testing / Quality AssurancesCountry: India
Interview Type: In-Person
#include <stdio.h>
#include <string.h>
int main(){
char buffer[1024];
char *s1 = "hello world";
char *s2 = "world";
char *s3 = "earth";
char *p;
if (!(p=strstr(s1, s2))) return s1;
strncpy(buffer, s1, p-s1);
buffer[p-s1]='\0';
sprintf (buffer+(p-s1), "%s%s", s3, p+strlen(s3));
printf("%s", buffer);
}
char *string_replace(char * orig, char * new, char * old)
{
int count = 0;
char * p, *q = NULL;
char *buff = NULL;
int orig_l = strlen (orig);
int new_l = strlen (new);
int old_l = strlen (old);
int buff_l = 0;
// Calculate the new buff size needed and allocate memory for the new buffer
if ( new_l != old_l) {
// Count the occurrence of the old string
for (count =0, p =orig ; ((q=strstr(p,old)) != NULL);p = q + old_l)
count ++;
buff_l = count * (old_l - new_l)+1+ orig_l;
buff = (char *) malloc ( buff_l * sizeof (char));
} else {
buff_l = orig_l;
}
// Now replace the old string with the new string
for ( count = 0, p = orig ; ((q = strstr(p,old)) != NULL); q = p + old_l) {
strncat(buff, orig, p - q);
strcat( buff, new);
}
// copy the left over in q to buff
strcat (buff,q)
return buff;
}
Forgot to put my name
char *string_replace(char * orig, char * new, char * old)
{
int count = 0;
char * p, *q = NULL;
char *buff = NULL;
int orig_l = strlen (orig);
int new_l = strlen (new);
int old_l = strlen (old);
int buff_l = 0;
// Calculate the new buff size needed and allocate memory for the new buffer
if ( new_l != old_l) {
// Count the occurrence of the old string
for (count =0, p =orig ; ((q=strstr(p,old)) != NULL);p = q + old_l)
count ++;
buff_l = count * (old_l - new_l)+1+ orig_l;
buff = (char *) malloc ( buff_l * sizeof (char));
} else {
buff_l = orig_l;
}
// Now replace the old string with the new string
for ( count = 0, p = orig ; ((q = strstr(p,old)) != NULL); q = p + old_l) {
strncat(buff, orig, p - q);
strcat( buff, new);
}
// copy the left over in q to buff
strcat (buff,q)
return buff;
}
Talked to her/authour, she didn't want want anything except strlen used (and wanted the logic to be easy just for her to learn to do brute force):
She dipped from collabedit session after I typed this mess so I'm going to post it here and give her the homework of fixing the 1000 bugs:
- S O U N D W A V E October 03, 2013