Microsoft Interview Question Developer Program Engineers
0of 0 votesRemove whitespace characters in a string, in place and with out shifting
Country: India
How about we fill the white spaces with null character('\0') and concatenate the sub strings.. plzz comment
concatenation of 2 strings requires O(m+n) extra space. so this approach is not inplace.
No we are not using extra space. we are splitting the string into substrings and concatenating at the same time.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string str = "how are you";
int n = str.Length;
int i=0;
char[] s = str.ToCharArray();
Console.WriteLine("Original string : " + str);
for (i = 0; i < n; i++)
{
if (s[i] == ' ')
s[i] = '\a'; // ascii for bell
}
Console.Write("String w/o space : ");
for (i = 0; i < n; i++)
Console.Write(s[i]);
Console.Read();
}
}
}
public static void removeSpace(char[] string) {
if (string == null || string.length == 0) {
return;
}
int p1 = 0;
int p2 = 0;
do {
while (p2 < string.length && string[p2] == ' ') {
p2++;
}
if (p2 == string.length) {
break;
}
string[p1++] = string[p2++];
} while (p1 < string.length && p2 < string.length);
for (int p = p1; p < string.length; p++) {
string[p] = 0;
}
for (char c : string) {
System.out.print(c + " ");
}
System.out.println();
}
logic correct, but question given than without shifting... otherwise it is very easy question not a MS question
@Anonymous talking about easy/MS: What does the question exactly mean? Care to elaborate?
you are not allowed to shift the characters from one location to another. here if there is space you are shifting the character from i to i-1 location... so total length of the string will be decreased but expected is should be of same length.
What does not shifting even mean? Can I shift from i+100 to i?
Ridiculous question.
A simpler way would be to ask for an O(n) time, in-place algorithm. Which I suspect it was, but OP managed to screw up.

- Anonymous on July 29, 2012 Edit | Flag Replychar s[] = "how are you"; int n = strlen(s); int i=0; while(s[i] != '\0') { if(s[i] == ' ') s[i] = 7; // ascii for bell i++; } cout << s << endl;