Interview Questions

replace all the spaces in a string with %20.

Microsoft Interview Questions and Answers


(Continued from previous question...)

37. replace all the spaces in a string with %20.

Question:
replace all the spaces in a string with %20


maybe an answer:

char* ReplaceString(const char* str) {
int strlen = 0, nspaces = 0;

while (str[strlen]) {
if (str[strlen] == ' ')
nspaces++;
strlen++;
}

int newLen = strlen + nspaces*2 + 1;
char * dst = new char[newLen];

int srcIndex=0,dstIndex=0;
while (str[srcIndex]) {
if (str[srcIndex] == ' ') {
dst[dstIndex++]='%';
dst[dstIndex++]='2';
dst[dstIndex++]='0';
++srcIndex;
} else {
dst[dstIndex++] = str[srcIndex++];
}
}

/*dst[dstIndex] = str[srcIndex]*/
dst[dstIndex] = '\0';

return dst;
}



maybe an answer2:

To edit the same string :

int main()
{
char str[1000];

while (cin.getline(str, 100))
{
int l=strlen(str),i,j;
for(i=0;i<l;i++)
{
str[l]='0';
if(str[i]==' ')
{
for(j=l-1;j>i;j--) str[j+2]=str[j];
str[i]='%';str[++i]='2';str[++i]='0';
l+=2;
}
}
str[l]='\0';
cout<<"Output : "<<str<<endl;
}
return 0;
}



maybe an answer3:

StringBuffer sb = new StringBuffer("This is a test string");
for(int i=0;i<sb.length();i++)
{
if(sb.charAt(i) == ' ')
{
String str1 = sb.substring(i+1, sb.length());
sb.delete(i, sb.length());
sb.append("%20");
sb.append(str1);
}
}

System.out.println(sb);

(Continued on next question...)

Other Interview Questions