Microsoft Interview Question
Software Engineer in TestsCountry: India
Interview Type: Written Test
Why use a new array. You can do it at the original array
public static void ReplaceFun(char[] str, int length) {
int spaceCount = 0, newLength, i = 0;
for (i = 0; i < length; i++) {
if (str[i] == β β) {
spaceCount++;
}
}
newLength = length + spaceCount * 2;
str[newLength] = '\0';
ν―ττττ
ττττττττττττττττττττττ
ττττττττττττττττττττττ
ττττττττττττττττττττττ
ττττττττττττττττττstr[newLength - 1] = β0βstr[newLength - 1] = β0βdsdc
for (i = length - 1; i >= 0; i--) {
if (str[i] == β β) {
str[newLength - 1] = β0β;
str[newLength - 2] = β2β;
str[newLength - 3] = β%β;
newLength = newLength - 3;
} else {
str[newLength - 1] = str[i];
newLength = newLength - 1;
}
}
}
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;
}
<pre lang="" line="1" title="CodeMonkey91764" class="run-this">int length=strlen(str);
for(int i=0;i<length;i++)
{
if(str[i]==' ')
{
length = length+2;
str[i]='%';
for(int j=length+1;j>i+2;j--)
str[j]=str[j-2];
str[i+1]='2';
str[i+2]='0';
}
}
str[length]='\0';
</pre><pre title="CodeMonkey91764" input="yes">
</pre>
//C#
static char[] ReplaceWithString(char[] _str)
{
int whiteSpaceCount = 0;
for (int i = 0; i < _str.Length; i++)
{
if (_str[i] == ' ')
{
whiteSpaceCount += 1;
}
}
char[] replacedString = new char[_str.Length + ((whiteSpaceCount * 3) - whiteSpaceCount)];
for (int i = 0,j =0; i < replacedString.Length; i++)
{
if (!(_str[j] == ' '))
{
replacedString[i] = _str[j];
}
else
{
replacedString[i] = '%';
replacedString[++i] = '2';
replacedString[++i] = '0';
}
j++;
}
return (replacedString);
}
For java, Can we not use String methods? Like str.replaceAll("\\s", "\\%20"). Sorry I am new to this forum, please correct me if am wrong.
What about this solution ?. I think it's easier than looping twice on the string
public String replace(String str)
{
if(str == null)
return null;
char[] word = str.toCharArray();
String temp="";
for(int i = 0 ; i < word.length; i++)
{
if(word[i] == ' ')
temp += "%20";
else
temp +=word[i];
}
return temp;
}
<pre lang="" line="1" title="CodeMonkey12888" class="run-this">char* ReplaceString(const char* str) {
- Anonymous September 14, 2011int 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;
}</pre><pre title="CodeMonkey12888" input="yes">
</pre>