Microsoft Interview Question
i have corrected bugs in the above code...
void truncate(char str[]){
int read=0,write=0;
//one extra for NULL, this is the max size if no extra spaces found
char buffer[strlen(str)+1];
while(str[read]){
if(str[read] == ' '){
buffer[write++]=' ';
while(str[read] && str[read]== ' '){
read++;
}
}
else{
buffer[write++]=str[read++];
}
}
buffer[write]='\0';
strcpy(str,buffer);
}
char* truncateExtraSpaceBetweenWords( char* str )
{
if (!str) return NULL;
if (!*str) return str;
char* ans = str;
int i = 0, j = 0;
while (1)
{
while(str[i] && str[i] == ' ') // remove all leading spaces
i++;
if (!str[i])
{
if (j == 0)str[j++] = ' ';
else if (str[j-1] == ' ') j--; // remove tailing spaces
str[j] = '\0';
return ans;
}
// move forward till you find non-space characters
while(str[i] && str[i] != ' ')
{
str[j++] = str[i++];
}
if (!str[i])
{
str[j] = '\0';
return ans;
}
else
{
str[j++] = str[i++]; // = ' '
}
}
}
package com.careercup;
public class TruncateConsecutiveSpaces_2991 {
public static void main(String[] args){
String stringToRidOfSpaces = "";
StringBuilder outputString = new StringBuilder();
stringToRidOfSpaces = "abc abc def";
int counter = 0;
char lastChar = '\0';
while(counter<stringToRidOfSpaces.length()){
char currentChar = stringToRidOfSpaces.charAt(counter);
if(lastChar == ' ' && currentChar == ' '){
System.out.println("Getting rid of this");
} else {
outputString.append(currentChar);
}
lastChar = currentChar;
counter++;
}
System.out.println(">>"+outputString+"<<");
}
}
void truncate(char str[]){
- Raman November 22, 2007int read=0,write=0;
//one extra for NULL, this is the max size if no extra spaces found
char buffer[strlen(str)+1];
while(str[read]){
if(str[read++] == ' '){
buffer[write++]=' ';
while(str[read]== ' ')
read++;
}
else{
buffer[write++]=str[read++];
}
}
buffer[write]='\0';
strcpy(str,buffer);
}