Interview Questions

int CutNPaste(char* str, int start, int stop, int destination)

Software QA/Tests Interview Questions from Microsoft


(Continued from previous question...)

int CutNPaste(char* str, int start, int stop, int destination)

Question:
int CutNPaste(char* str, int start, int stop, int destination)


maybe an answer1:


#include <stdio.h>

// Provided destination does not come inbetween start and stop
int CutNPaste(char* str, int start, int stop, int destination)
{
int length = stop - start + 1;
char *temp = new char[length];

for (int i = 0; i < length; ++i)
{
temp[i] = str[start + i];
}

for (int i = 0; i < destination - stop; ++i)
{
str[start + i] = str[stop + i + 1];
}

for (int i = 0; i < length; ++i)
{
str[destination - length + i] = temp[i];
}
}

int main()
{
char *str = "jump the over wall";
CutNPaste(str, 4, 7, 13);
printf("%s", str);
return 0;
}



maybe an answer2:


int CutNPaste(char* str, int start, int stop, int dest)
{ char temp;
int length = stop - start + 1;
Reverse(str, start, stop);
Reverse(str, stop + 1, dest + length - 1);
for (int i = 0; i < length; ++i)
{
temp = str[start + i];
str[start + i] = str[dest + length - i - 1];
str[dest + length - i - 1] = temp;
}
if (dest > stop)
{
Reverse(str, stop + 1, dest - 1);
}
else
{
CutNPaste(str, stop - (stop - dest), dest - 1, dest + length - (stop - dest));
}
}

void Reverse(char *str, int start, int stop)
{
for (int i = start; i < (start + stop + 1) / 2; ++i)
{
char temp = str[i];
str[i] = str[stop - (i - start)];
str[stop - (i - start)] = temp;
}
}

(Continued on next question...)

Other Interview Questions